Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use RewriteCond based on environment variable in .htaccess

I am trying to define an environment variable in my .htaccess file, and then run a rewrite condition using that variable. Below is what I have in my .htaccess file, but the rewrite is not working:

RewriteEngine on
#set to 'live' or 'maintenance'
SetEnv ENVIRONMENT maintenance

#If the ENVIRONMENT variable is 'mainetnance' then show a maintenance page to the users
RewriteCond %{ENV:ENVIRONMENT} maintenance
RewriteRule ^(.*)$ /maintenance.html

The purpose of this is to set the site to maintenance mode programmatically by having PHP edit the .htaccess file when it receives a post request from one of GitHub's hooks to pull the repo for an update.

like image 819
Brandon Rohde Avatar asked Jul 25 '13 08:07

Brandon Rohde


People also ask

What is RewriteCond in htaccess?

htaccess rewrite rules can be used to direct requests for one subdirectory to a different location, such as an alternative subdirectory or even the domain root. In this example, requests to http://mydomain.com/folder1/ will be automatically redirected to http://mydomain.com/folder2/.

What is RewriteCond %{ Request_filename?

RewriteCond %{REQUEST_FILENAME} !-f. RewriteCond %{REQUEST_FILENAME} !-d. … means that if the file with the specified name in the browser doesn't exist, or the directory in the browser doesn't exist then procede to the rewrite rule below.

What is NC in RewriteCond?

NC = nocase means regardless of the case of the incoming referrer traffic match with the given pattern. See Apache [NC|nocase] flag.

What is mod_rewrite in Apache?

The mod_rewrite module uses a rule-based rewriting engine, based on a PCRE regular-expression parser, to rewrite requested URLs on the fly. By default, mod_rewrite maps a URL to a filesystem path. However, it can also be used to redirect one URL to another URL, or to invoke an internal proxy fetch.


2 Answers

mod_rewrite doesn't use variables set via SetEnv, instead use this method:

#set to 'live' or 'maintenance'
RewriteRule .* - [E=STATUS:maintenance]

#If the ENVIRONMENT variable is 'maintenance' then show a maintenance page
RewriteCond %{REQUEST_URI} !maintenance.html [NC]
RewriteCond %{ENV:STATUS} ^maintenance$
RewriteRule ^.*$ /maintenance.html [L]

The first line of the bottom three, makes sure that once the user is redirected to the file "maintenance.html", it will not be redirected again. Else the user keeps getting redirected to the same file, causing an 500 internal server error saying "AH00124: Request exceeded the limit of 10 internal redirects due to probable configuration error."

like image 179
Jeffrey Avatar answered Sep 19 '22 05:09

Jeffrey


Bit late - but for all the others searching ...

use SetEnvIf - see: mod_rewrite rule and setenv

SetEnvIf Request_URI ".*" ENVIRONMENT=maintenance

...

like image 37
user5682299 Avatar answered Sep 19 '22 05:09

user5682299