Skip to content
Advertisement

.htaccess RewriteRule keeping URL structure

My current rewrite rule:

RewriteEngine on
RewriteRule ^([^/.]+)/([^/.]+)/([^/.]+)?$ index.php?a=$1&v=$2&id=$3 [L]

The result above works great so I can format the URL like

domain.com/a/b/c

I would like to add in a domain switch as well so the results I want is

sub.domain.com/a/b/c when you access it using domain.com/a/b/c

Currently here is what I have tried

RewriteEngine on
RewriteRule ^([^/.]+)/([^/.]+)/([^/.]+)?$ index.php?a=$1&v=$2&id=$3 [L]
RewriteCond %{HTTP_HOST} ^domain.com$ [OR]
RewriteCond %{HTTP_HOST} ^www.domain.com$
RewriteRule (.*)$ http://sub.domain.com/ [R=301,L]

But the result of this is

http://sub.domain.com/a=a&v=b&id=c

and needs to be

http://sub.domain.com/a/b/c

Thanks for the help!!

Advertisement

Answer

Reverse the order of your rules:

RewriteEngine on

RewriteCond %{HTTP_HOST} ^(www.)?domain.com$ [NC]
RewriteRule (.*)$ http://sub.domain.com/$1 [R=301,L]

RewriteRule ^([^/.]+)/([^/.]+)/([^/.]+)?$ index.php?a=$1&v=$2&id=$3 [L,QSA]

Make sure to test this after clearing your browser cache.

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement