Using SetEnvIf in .htaccess with sub-domain
Here's a quick hint on how to easily use the SetEnvIf in .htaccess with multiple sub-domain.
If you use sub-domain for languages or you using sub-domain to differentiate mobile versus non-mobile version of your site, you can simply use the SetEnvIf and then use it in your code.
Let say you have a multi-language website setup like this:
- www.domain.com
- en.domain.com
- fr.domain.com
- es.domain.com
The idea here is to assign a variable to the apache environment and then pass it to the script or using the environment variables if available.
RewriteEngine On
RewriteBase /
SetEnvIf Host ^www\. lang=en
SetEnvIf Host ^en\. lang=en
SetEnvIf Host ^fr\. lang=fr
SetEnvIf Host ^es\. lang=es
# other rules ...
RewriteRule ^([a-z0-9_\-]+)/?$ index.php?lang=%{ENV:lang}&page=$1 [L,NC,QSA]
The %{ENV:lang} will be read from the SetEnvIf (from the sub-domain) and set the correct language you will get from $_GET['lang']; (in your PHP code - assuming it's PHP)
This way, any of the sub-domain will be dynamically loaded without creating rules over and over for sub-domain. I also added a rule that prevent loading images or JavaScript as page.




