Set env variable in htaccess – Create Apache Environment variable via htaccess

Set env variable in htaccess – Create Apache Environment variable via htaccess

You can set an environment variable using your htaccess file. There are two ways to do this via an htaccess.

  • RewriteRule
  • SetEnv directive

Setting env variable via RewriteRule

To set env variable through a RewriteRule, you need to use E flag. Syntex for the E flag is as follows
E=variable:value .

The following is basic mod rewrite example to set an environment variable. You can test the code on your live server to see how it works :

RewriteEngine on
RewriteRule (.*) – [E=foo:bar]

The rule above sets an env variable with foo as variable name and bar as variable value.

Set env variable via env directives

ENV can also be created by using directives that are especially designed for env purposes. The following directives are used for creating ENV :

  • SetEnvIf
  • SetEnvIfNoCase

SetEnvIf directive uses a regular expression based pattern to match against mod rewrite variable and you can set the variable based on mod rewrite server variable.
The following code sets an env named pageviews and value 2 when /foo/ uri is requested.

SetEnvIf Request_uri “^/foo/$ pageviews=2

SetEnvIfNoCase is same as SetEnvIf except for one thing. Nocase makes the pattern case insensitive meaning that the ^/foo/$ will also match /FOO/.

Tags: ,

Leave a Reply

Your email address will not be published. Required fields are marked *