6

The URL I'm using is, let's say, example.com/subdir/index.php?foo=bar

index.php contains this: <?php echo getenv("testenvvar"); ?>

I'm setting an enviroment variable in .htaccess like so:

SetEnvIf Request_URI (index) TestEnv=Worked

This prints "Worked".

If I change it to SetEnvIf Request_URI (bar) TestEnv=Worked, it does not.

How can I do this?

anubhava
  • 761,203
  • 64
  • 569
  • 643
Duncan Marshall
  • 530
  • 1
  • 6
  • 15
  • 1
    You are trying to access a string from the query arguments, that won't work. The query part simply is _not_ part of the `RequestURI`! This is clearly stated in the documentation: http://httpd.apache.org/docs/current/mod/mod_setenvif.html#setenvif That documenation actually points out specifically, where you can find an answer to your question :-) – arkascha Jul 10 '15 at 14:06
  • 2
    I'd read that documentation, but it conflicted with my testing. In any case, it didn't yield me the answer. Apparently I should use RewriteCond, but I don't see how. – Duncan Marshall Jul 10 '15 at 14:14
  • See here: http://stackoverflow.com/questions/19362746/rewritecond-with-setenv which refers to there: https://turboflash.wordpress.com/2010/05/27/apache-environment-variables-visibility-with-setenv-setenvif-and-rewriterule-directives/ – arkascha Jul 10 '15 at 14:23

4 Answers4

8

Another option would be SetEnvIfExpr:

SetEnvIfExpr "%{QUERY_STRING} =~ /bar/" TestEnv=Worked
Kevinoid
  • 4,180
  • 40
  • 25
4

To match query string you will need mod_rewrite rules instead of mod_setenv.

Place this code in root .htaccess:

RewriteEngine On

RewriteCond %{QUERY_STRING} bar [NC]
RewriteRule ^ - [E=TestEnv:Worked]
anubhava
  • 761,203
  • 64
  • 569
  • 643
  • 1
    it would be nice if you explained what is going on. [NC] means case insensitive, ^ - means don't change the url, just set and environment variable, – santiago arizti Jul 07 '17 at 23:23
  • `NC` is for ignore case match. It will match bar, Bar, BAR , baR etc in above example. – anubhava Jul 08 '17 at 06:16
2

Let me explain more detailed how I applied it.

Assume we want to add a X-Robots-Tag header when the following URL is being requested: https://example.com/?whatever=true

This can be achieved by adding the following rules to the .htaccess file:

RewriteEngine On
RewriteCond %{QUERY_STRING} /?whatever=true$ [NC]
RewriteRule ^ - [E=NOINDEXFOLLOW:true]
Header set X-Robots-Tag "noindex, follow" env=NOINDEXFOLLOW
BVB Media
  • 307
  • 3
  • 4
0

Using SetEnvIfExpr and REDIRECT_NOINDEXFOLLOW works for me.

RewriteEngine On
SetEnvIfExpr "%{QUERY_STRING} =~ /bar/" NOINDEXFOLLOW
Header set X-Robots-Tag "noindex, follow" env=REDIRECT_NOINDEXFOLLOW
Mau
  • 1,257
  • 2
  • 15
  • 21