Apache Environment Variable – Setting on Mod_Rewrite Condition

apache-2.2mod-rewriterewrite

My rewrite rule is working and redirecting requests like /versioned/1234/images/foo.gif to /images/foo.gif but it doesn't seem to be setting the set_expires_header environment variable because the headers are not being appended. If I uncomment the line that explicitly sets the environment variable then the headers are set. What am I doing wrong? Is there a better way to do this? I want to be able to access the files with both URLs but only have the headers added when accessing it through the versioned URL.

<VirtualHost *:80>
   ServerName dev.example.com
   DocumentRoot /var/www/html/dev

   <Directory "/var/www/html/dev">
      Options FollowSymLinks ExecCGI
      AllowOverride All
      Order allow,deny
      Allow from all

      SetEnvIf Request_URI versioned set_expires_header

      RewriteEngine on
      RewriteRule ^versioned/[^/\.]+/(.*)$ /$1 [E=set_expires_header:true,L]

      #SetEnv set_expires_header true
      Header append Expires "access plus 1 year" env=set_expires_header
      Header append Cache-Control "public" env=set_expires_header
   </Directory>
</VirtualHost>

Best Answer

The reason the above configuration isn't working is that the Header lines are evaluated before the RewriteRule and thus the environment variable is always null.

The solution is to move the RewriteRule outside the <Directory> block so that it is evaluated before the Header lines.

See Serving Javascript Fast for more details

Here is the final working configuration:

<VirtualHost *:80>
   ServerName dev.example.com
   DocumentRoot /var/www/html/dev

   RewriteEngine on
   RewriteRule ^versioned/[^/\.]+/(.*)$ /$1 [E=set_expires_header:true,L]

   <Directory "/var/www/html/dev">
      Options FollowSymLinks ExecCGI
      AllowOverride All
      Order allow,deny
      Allow from all

      Header append Expires "Mon, 28 Jul 2014 23:30:00 GMT" env=set_expires_header
      Header append Cache-Control "public" env=set_expires_header
   </Directory>
</VirtualHost>