Sign up ×
Webmasters Stack Exchange is a question and answer site for pro webmasters. It's 100% free, no registration required.

I'm having problems with the following config on my Apache server to Rewrite some URLs.

SetEnv PATH_TO_DIR /directory

RewriteRule ^%{PATH_TO_DIR}/([a-zA-Z0-9_\-]+)/([a-zA-Z0-9_\-\.]+)/?$ /index.php?dir=$1&file=$2

ErrorDocument 404 %{PATH_TO_DIR}/index.php?dir=null&file=error

This config used to work perfectly until I used SetEnv PATH etc. I need to use this because there are lots of rules, not just those mentioned above.

Can anyone point out my mistake?

Apache returns


when I try anything ( for instance).

Apache returns the ErrorDocument if I just try to fetch the index.

I know it's not a problem with the rewrite rules because they work when I remove the PATH_TO_DIR variable and just hard code it.

share|improve this question

migrated from Feb 21 '11 at 21:39

This question came from our site for system and network administrators.

3 Answers 3

You can't use per-request variables, like the ones created by SetEnv, in the regex of a RewriteRule. The Regex is compiled at startup.

You can only use variables, with the proper syntax, in the substitution of a rewriterule (2nd parm)

share|improve this answer
In fact, you can't use variables set with SetEnv (mod_env) anywhere in mod_rewrite since it executes too late in the request. You would need to set the environment variable with SetEnvIf (mod_setenvif) which executes much earlier. – w3d Oct 31 at 11:40

Should not %{PATH_TO_DIR} be %{ENV:PATH_TO_DIR}? Also, I am not certain that you can use those variables on the rule, I think they can be used only on the RewriteCond.

Give it a look here and here, specially on that phrase:

If you wish to match against the hostname, port, or query string, use a RewriteCond with the %{HTTP_HOST}, %{SERVER_PORT}, or %{QUERY_STRING} variables respectively

share|improve this answer
"can be used only on the RewriteCond" - Only in the RewriteCond TestString and the RewriteRule substitution (ie. not in a regex). – w3d Oct 31 at 11:29

To add to covener's analysis:

You can use environment variables when using rewrites, but as you mention, SetEnv doesn't retain that info (to my knowledge). I've had good success using forced variable injections in my start up scripts. For example, when calling the apachectl or httpd binaries, you can do something like:

In your shell script do (i use in case syntax, and add an option for startMaint):

MAINTENANCE=TRUE ${APACHE_ROOT}/bin/apachectl -d ${APACHE_ROOT} -f ${APACHE_CONF} -k start

RewriteCond %{REQUEST_FILENAME} !\.(gif|jpg|png|ico)$ [NC]
RewriteCond %{REQUEST_URI} ^/(status|uri1|uri2|uri3|etc).*$ [NC]
RewriteCond %{REQUEST_URI} !^/static/siteMaintenance.html$ [NC]
RewriteRule .* /static/siteMaintenance.html${pages:%1:NULL}? [R=302,L]
share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.