When you set a server environment variable in your Apache settings, it's possible to read that variable from PHP using built in functions.
But can you read the variable from an htaccess file?
What I'm trying to accomplish in my htaccess is something along the lines of:
<If var=="stuff">
do things here
</if>
<if var=="different stuff">
do different things here
</if>
Yes it is.
You will probably want to use mod_setenvif functionality, so that module will need to be turned on.
Then you simply do something like:
Which would set the environmental variable
image_type
with a value ofgif
if the requested file name ends with.gif
.You could then access this (like in RewriteCond) like this:
You can read the full documentation here: http://httpd.apache.org/docs/2.2/env.html
Apache 2.4 introduced
<If>
,<Else>
,<ElseIf>
blocks in conjunction with a new expression syntax for more powerful programmatic control in .htaccess files, etc.This is untested but ostensibly works:
Source: https://blogs.apache.org/httpd/entry/new_in_httpd_2_4
As I had a lot of problems setting up a similar thing to recognise my home localhost as distinct to my work set up, here's what I ended up doing.
First and foremost, The
<IF ..>
directive does not recognise SetEnv. From http://httpd.apache.org/docs/current/env.html : "The SetEnv directive runs late during request processing meaning that directives such as SetEnvIf and RewriteCond will not see the variables set with it."So, try to use SetEnvIf if you can. I was lazy and just put this in my httpd.conf file. It checks that it's running on localhost - which is obviously is - then sets the variable:
Then, elsewhere, in my htaccess file I had this:
Alternatively, you could just have one variable for each environment and give it a specific value:
Then the rest would be the same, except that first
<If ..>
statement:I've tested both of those between a home environment with 2.4 and a work environment with 2.2, both of which had mod_version enabled (hence not bothering with the ifmod).
(I also haven't tested for more than two environments but Apache 2.4 does give an
<ElseIf>
so that's also an option).Doop di do.
(More about the -T operator et al: http://httpd.apache.org/docs/current/expr.html)
I gave description and .htaccess and PHP examples here: Set an environment variable in .htaccess and retrieve it in PHP
For just some examples in .htaccess, taken from my modifying the Perishable Press 5G Blacklist/Firewall http://perishablepress.com/5g-blacklist-2013/ to use environment variable reporting:
Notice the use of paramters. %0 gives the full string, %1 gives the match from the 1st parenthesized statement, %2 the 2nd. The hyphens are literal display characters, to visually separate (don't think is any way to put spaces in there).