Can mod-rewrite be used to set environmental variables?

Posted by VLostBoy on Server Fault See other posts from Server Fault or by VLostBoy
Published on 2010-07-27T15:23:25Z Indexed on 2011/02/08 15:27 UTC
Read the original article Hit count: 192

Filed under:
|
|

Hi, I've got an existing simple rewrite rule like so:

<Directory /path>
    RewriteEngine on
    RewriteBase /

    # if the requested resource does not exist
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d

    # route the uri to a front controller
    RewriteRule ^(.*)$ index.php/$1 [L]
 </Directory>

This works fine, but I want to do one of either two things. On the basis of detecting the clients accept-language header, I want to either

(i) Set the detected language as an environmental variable that the script can use or

(ii)Rewrite the request so that the url begins with the language code (e.g. www.example.com/en/some/resource)

In terms of implementing (i), I defined this rule:

<Directory /path>
    RewriteEngine on
    RewriteBase /

    # if the requested resource does not exist
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d

    # if the users preferred language is supported...
    RewriteCond %{HTTP:Accept-Language} ^.*(de|es|fr|it|ja|ru|en).*$ [NC]
    # define an environmental variable PREFER_LANG
    RewriteRule ^(.*)$ - [env=PREFER_LANG:%1]    

    # route the uri to a front controller
    RewriteRule ^(.*)$ index.php/$1 [L]
 </Directory>

I've tried a few variations, but PREFER_LANG is not defined in $_SERVER nor retrievable by getenv.

In terms of implementing (ii)... lets just say its messy. I'll post it if I can't get an answer to one.

Can anyone advise me? Thanks!

© Server Fault or respective owner

Related posts about apache

Related posts about mod-rewrite