Nabi K.A.Z.
Nabi K.A.Z.

Reputation: 10714

.htaccess redirect domain to sub domain with keep file name and params

I want use .htaccess to redirect these examples:

example.com
example.com/forum
www.example.com
www.example.com/forum

to this:

forum.example.com

I write this:

RewriteCond %{HTTP_HOST} !^forum\.example\.com$ [NC]
RewriteRule ^ http://forum.example.com [R=301,L]

It's good but I want keep file name and params in url. so I change it to this:

RewriteCond %{HTTP_HOST} !^forum\.example\.com$ [NC]
RewriteRule ^(.*)$ http://forum.example.com/$1 [R=301,L]

It's ok, and for example when I goto this url:

http://example.com/viewforum.php?f=2

redirect to:

http://forum.example.com/viewforum.php?f=2

But when I goto this:

http://example.com/forum/viewforum.php?f=2

redirect to this:

http://forum.example.com/forum/viewforum.php?f=2

but this target url is not correct and must be like this:

http://forum.example.com/viewforum.php?f=2

How can fix it?

Thanks

Upvotes: 0

Views: 412

Answers (1)

showdev
showdev

Reputation: 29168

How about something like this:

RewriteCond %{HTTP_HOST} !^forum\.example\.com$ [NC]
RewriteRule ^(?:forum\/)?(.*)$ http://forum.example.com/$1 [R=301,L]

Upvotes: 1

Related Questions