开发者

Replace parts of the URL with mod_rewrite

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 domainnam开发者_运维问答e.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?


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜