1

We have a php-based website and want to set an env variable based on host and the first part of the request uri. The site is running apache with mod_rewrite and fpm.

I found SetEnvIfExpr and tried to add this to the .htaccess:

SetEnvIfExpr "%{HTTP_HOST} =~ m#.*example.com.*# && %{REQUEST_URI} =~ m#^/de.*#" RUN_CODE=german

I want to match all urls starting with example.com/de.

Doing a var_dump($_SERVER['RUN_CODE']); in my index.php gives me NULL.

Through trial and error I figured out the following:

  • When I modify the last request (the one matching REQUEST_URI) to ^.*de.* it works correctly. Sadly, that's not really a solution because this could match other urls not starting with /de.
  • I suspected this issue comes from the processing order of mod_setenvif and mod_rewrite. var_dump($_SERVER['REQUEST_URI']); gives me only /de/... but I found that modifying the regex to ^/in.*de.* matches. ^/index.php/de.* does not.
kolaente
  • 1,252
  • 9
  • 22

1 Answers1

2

If rewriting the URL causes an internal redirect, Apache renames your env variable from RUN_CODE to REDIRECT_RUN_CODE.

This is common behavior of the Apache2 webserver, compare:

So as it looks like you're building on top of the effect of an internal redirect, from PHP's end the variable name is different:

var_dump($_SERVER['REDIRECT_RUN_CODE']); # instead of 'RUN_CODE'
hakre
  • 193,403
  • 52
  • 435
  • 836
bobkorinek
  • 646
  • 3
  • 16
  • Looks like that's it. Now I just need to figure out how to tell the application to use `$_SERVER['REDIRECT_RUN_CODE']` (that part is handled by a framework) – kolaente Nov 02 '21 at 09:04
  • Would be better to avoid the redirect :-D of course you could patch the app's index.php to $_SERVER['RUN_CODE'] = $_SERVER['REDIRECT_RUN_CODE'] or put a later SetEnv in .htaccess ? – Alex Nov 02 '21 at 14:27
  • I am wondering which redirect causes the variable renaming ... The linked post talks about setting env variables in `RewriteRule`s, but you are using `SetEnvIfExpr` ... – Alex Nov 02 '21 at 14:36