Tag Archives: backreference

Save RewriteCond’s backreferences to use in RewriteRule

Using Apache’s mod rewrite, it’s possible to redirect URL and stuff. One cool thing is to use backreferences and use them as environment variables. For example when you have several RewriteRule sharing some common part(s) but are different … the bad example under will, I hope, be clearer.

	# in .htaccess or vhost
	RewriteEngine On
	# define a RewriteCond with two capturing part
	RewriteCond %{HTTP_HOST} ^(.+?).(test|prod).com$ [NC]
	# there we define the value of the subdomain (i.e %1) and the host (i.e %2 which can be test or prod)
	RewriteRule .? - [E=SUBDOMAIN:%1,E=HOST:%2]
	# we apply the RewriteRule using our variables
	RewriteRule ^js/(.+?).js$ %{ENV:SUBDOMAIN}.php?js=$1&host=%{ENV:HOST} [L]
	RewriteRule ^css/(.+?)/(.+?).css$ %{ENV:SUBDOMAIN}.php?folder=$1&css=$2 [L]
	
	# other useless example of how to do so
	RewriteCond %{HTTP_USER_AGENT} ^(Mozilla.+) [NC]
	RewriteRule .? - [E=HASMOZILLA:%1]	
	
	RewriteCond %{REMOTE_ADDR} =127.0.0.1
	RewriteRule ^here$ %{ENV:SUBDOMAIN}.php?who=me [L]

Basically the part to remember is this trick wich allows to save environment variables:

        RewriteRule .? - [E=VAR1_NAME:VALUE,E=VAR2_NAME:VALUE]

Do not put any space between values, this example will give an internal error (space after the comma):

        RewriteRule .? - [E=VAR1_NAME:VALUE, E=VAR2_NAME:VALUE]

And if you have a RewriteCond above with capturing part(s), you can use backreference (%1 and so on), just like in the first example.

Finally, you can use the environment variable in your RewriteRule like so:

        %{ENV:VAR_NAME}

VoilĂ  !