Problem with mod_rewrite

Tag: apache , mod-rewrite , redirect , rules Author: tinaleung0608 Date: 2010-09-01

I need a mod_rewrite rule to redirect url depending on the hostname they are comming from.

The situation:

We have multiple domains pointing to a same webspace and we need to restrict what the specific host can see/download.

domainname.com/images/logo.jpg and /www.domainname.com/images/logo.jpg should transform into domainname.com/domainname_com/images/logo.jpg

So basically I need a rule/function that replaces the dots in the %{HTTP_HOST} with _ and removes/replaces the www subdomain.

Is there any way to do this with mod_rewrite?

Other Answer1

You could just use virtual hosts configuration.

comments:

That isn't a possibility in this case.

Other Answer2

Try these rules:

RewriteCond %{ENV:DOMAIN_DIR} ^$
RewriteCond %{HTTP_HOST} ^(www\.)?(.+)
RewriteRule ^images/.+ - [E=DOMAIN_DIR:%2]

RewriteCond %{ENV:DOMAIN_DIR} ^([^.]*)\.(.+)
RewriteRule ^images/.+ - [E=DOMAIN_DIR:%1_%2,N]

RewriteCond %{ENV:DOMAIN_DIR} ^[^.]+$
RewriteRule ^images/.+ %{ENV:DOMAIN_DIR}/$0 [L]

The first rule will take the host and store it without www. in the environment variable DOMAIN_DIR. The second rule will replace one dot at a time; the N flag allows to restart the rewriting process without incrementing the internal recursion counter. Finally, the third rule will rewrite the request to the corresponding directory.