.htaccess variables
Aug. 30th, 2012 09:20 pmYou can set variables inside an Apache .htaccess file. To copy directly from someone else's example:
RewriteCond %{REQUEST_URI} ^/category_abc/
RewriteRule .* - [E=cat_id:1]
RewriteCond %{REQUEST_URI} ^/category_def/
RewriteRule .* - [E=cat_id:2]
- The E= tells Apache we're creating a new ENV variable.
- The cat_id is the name of the variable we're creating
- The :x is the value of the variable (simple key : value syntax).
And from another example:
RewriteCond %{HTTP:Accept-Language} ^.*(de|es|fr|it|ja|ru|en).*$ [NC]
RewriteRule ^(.*)$ - [env=lang:%1]
Set lang var to URI
RewriteEngine On
RewriteBase /
RewriteCond %{THE_REQUEST} ^[A-Z]{3,9}\ /(.+)/(de|es|fr|it|ja|ru|en)/\ HTTP/ [NC]
RewriteRule ^(.*)$ - [env=lang:%2]
Environment variables are referenced as %{ENV:varname}. How they are used is another story. There are places you can't use them.
# Make a variable for RewriteBase
RewriteCond "/base_dir/" ^(.*)$
RewriteRule ^(.*)$ - [E=RewriteBase:%1]
# Fails, causes an internal server error.
RewriteBase %{ENV:RewriteBase}
You can't do this either:
# RequestPrefix is a previously declared variable.
RewriteCond %{REQUEST_URI} ^%{ENV:RequestPrefix}(.*)$
RewriteRule ^(.*)$ - [E=RequestSuffix:%1]
A quick web search finds someone claiming that rewrite condition patterns are compiled before variables are interpreted.