Using Apache environment variables in .htaccess

In a previous post I talked about using environment variables to make your life easier when developing on multiple servers. In this post I will talk about how to use these variables in your .htaccess file.

Why .htaccess?

You may want some rules specific to different servers, maybe you want to hide certain paths on your live server, or perhaps you want to use a different robots.txt file. Below is a rule I’ve used to server a different robots file on a live server.

RewriteCond %{ENV:TESTSERVER} !yes
RewriteCond %{REQUEST_URI} robots.txt
RewriteRule (.*) robots.txt.block
  • Is the environment variable ‘TESTSERVER’ NOT equal to ‘yes’?
    • I’m checking ‘TESTSERVER’ is equal not to yes, this will ensure that if the variable is not set at all we do not process this rule. We want not using this rule to be the safe default.
  • Is the robots.txt file being requested?
    • I want this rule to only affect one file.
  • Serve up a different robots.txt file.

Setting the environment variable

You can’t just do this with ‘SetEnv’ in your apache config file! If you try this, your rewrite condition will never be met. This is because the variable is assigned after .htaccess is used. Luckily there is a very simple way around this:


Using ‘SetEnvIf’ will set the environment variable in time for htaccess to utilise it. You don’t have to provide a full if condition, however you certainly can if needed. The rule above is basically an if true, this will always set the ‘TESTSERVER’ variable to ‘yes’


Published by


I am a Web Developer who has been creating websites and hacking at WordPress for over 4 years. I'm a graduate of Surrey University where I studied Computer Science.

Find me on linked in