Forum Moderators: phranque

Message Too Old, No Replies

mod_rewrite question

Easy one for mod_rewrite gurus

         

storevalley

9:25 am on Sep 15, 2004 (gmt 0)

10+ Year Member



Hi Guys ...

I know that this will redirect from a subdirectory of one domain directly to another ...

RewriteRule ^subdir(.*)$ [domain.co.uk$1...] [flags]

... but how do you use mod_rewrite to create the opposite effect, e.g. to redirect all traffic from one domain to a subdirectory of another, preserving the rest of the URL?

Would that be ...

RewriteRule ^(.*)$ [domain.co.uk...] [flags]

jdMorgan

12:40 pm on Sep 15, 2004 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



That will work, as long as the domains are separately-hosted. If not, you have the potential of creating an infinite loop, because the RewriteRule pattern will match both before and after the redirect, so the redirected request will get redirected again.

To avoid that, you'll need to add a RewriteCond to disable the rule if the request is already being made to the "correct" domain:


RewriteCond %{HTTP_HOST} !^www\.domain\.co\.uk
RewriteRule ^(.*)$ http://www.domain.co.uk/subdir/$1 [flags]

Note that because of the form of your first example, I assume that you are placing the code in .htaccess as opposed to httpd.conf. If not, delete the slash preceding "$1" in the rule above.

Things get a lot more complex if you have multiple subdomains -- too many to conveniently add manually -- or even worse, a situation where any number of subdomains may be needed, such as giving users their own subdomains. In those cases, this thread on how to redirect any number of arbitrarily-named subdomains to subdirectories [webmasterworld.com] may be helpful.

Jim

storevalley

2:13 pm on Sep 15, 2004 (gmt 0)

10+ Year Member



Many thanks Jim ...

Had just got exactly the code you just posted working in .htaccess, and was going to post the solution back myself. It's good to verify that there isn't something else 'orrible I haven't spotted yet, though :)

The info about subdomain complications is most useful too. There aren't any in this case, but the info will (I am sure) save me a few minutes at some point in the future!