Using custom environment variables in .htaccess

烂漫一生 提交于 2019-12-30 10:14:20

问题


I need something like this:

SetEnv foo bar.baz
RewriteEngine On

RewriteCond %{HTTP_HOST} ^%{foo}$
RewriteRule ^(.*)$ http://www.foo/$1 [L]

UPD:

I have made as follows:

SetEnv HOSTNAME_ENV testsite
RewriteEngine On
RewriteCond %{HTTP_HOST} ^%{ENV:HOSTNAME_ENV}
RewriteRule ^(.*)$ http://www.%{ENV:HOSTNAME_ENV}/$1 [L,R=301]

But it doesn't work. %{ENV:HOSTNAME_ENV} is not defined.


回答1:


This won't work, because mod_rewrite does not expand variables in test patterns. Consequently, your expression will attempt to match the regular expression ^%{foo}$, not ^value_of_foo$.

Additionally, the documentation for SetEnv also makes a special note about order-of-processing in relationship to mod_rewrite. This actually does come into play here, despite the rules being applied later in the request handling than the scenario they're describing there. If you don't perform a rewrite that causes an internal redirection before testing against the environment variable you set, it will be blank.

Assuming you set the variable correctly, a potential workaround is to do this, although I feel like it isn't foolproof:

RewriteCond %{HTTP_HOST}#%{ENV:foo} ^([^#]+)#\1$



回答2:


Just set the environment using rewrite rules:

RewriteRule (.*) $1 [E=HOSTNAME_ENV:whatever.com]

This has also the advantage, that you are able to use RewriteCond.



来源:https://stackoverflow.com/questions/3627411/using-custom-environment-variables-in-htaccess

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!