Htaccess RewriteCond based on environment variable

Htaccess RewriteCond based on environment variable - .htaccess files are extremely useful in many cases for users who either do not have root permissions or for users who simply aren't comfortable in making changes in their web server's configuration file. Trying to debug .htaccess not working isn't always the easiest thing to do, however, hopefully by checking the discuss below mentioned about htaccess, apache, mod-rewrite, custom-variables, .htaccess common problems as well as the troubleshooting tips, you'll have a better grasp on what you may have to modify to get your .htaccess file running smoothly.Problem :


I find apache very unfriendly.


Anyway. I have this:


RewriteRule (.*) - [QSA,E=DOMAIN_NAME:localhost.com]

This doesn't redirect, which is fine:


RewriteCond "www.%ENV:DOMAIN_NAME" "!=www.localhost.com"
RewriteRule ^ https://%HTTP_HOST?err=%ENV:DOMAIN_NAME [L,R=301]

This doesn't redirect, which is fine:


RewriteCond "%HTTP_HOST" "!=www.localhost.com"
RewriteRule ^ https://%HTTP_HOST?err=%ENV:DOMAIN_NAME [L,R=301]

This does redirect:


RewriteCond "www.%ENV:DOMAIN_NAME" "!=%HTTP_HOST"
RewriteRule ^ https://%HTTP_HOST?err=%ENV:DOMAIN_NAME [L,R=301]

Is very frustrating. I'm stuck in checking two variables if they match...


Solution :


This does redirect:


RewriteCond "www.%ENV:DOMAIN_NAME" "!=%HTTP_HOST"


Because server variables of the form %VARNAME are not expanded in the CondPattern (2nd argument to the RewriteCond directive). You are comparing against the literal string "%HTTP_HOST", which is obviously different to "www.localhost.com", so the condition is successful.


You need to use a regex with an internal backreference instead. For example:


RewriteCond www.%ENV:DOMAIN_NAME@%HTTP_HOST !^([w.]+)@1$

Where @ is just an arbitrary character that does not occur elsewhere in the string being checked. And 1 is a backreference to the captured subpattern, ie. ([w.]+).


Or use an Apache Expression (Apache 2.4):


RewriteCond expr "'local.%ENV:DOMAIN_NAME' != %HTTP_HOST"

Aside:



RewriteRule (.*) - [QSA,E=DOMAIN_NAME:localhost.com]


If you are simply setting an env var then you don't need to capture (or even match) the entire URL-path and the QSA flag is superfluous (since there is no substitution). For example:


RewriteRule ^ - [E=DOMAIN_NAME:localhost.com]

Additionally, if you would like to do some further testing, give the htaccess tester tool a try. It allows you to specify a certain URL as well as the rules you would like to include and then shows which rules were tested, which ones met the criteria, and which ones were executed.

Comments

Popular posts from this blog

Rewrite in Mediawiki, remove index.php, .htaccess

.htaccess rewrite wildcard folder paths from host

Using .htaccess to set a cookie and 301 redirect