Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how can I define variable in .htaccess file and use it?

I have defined an htaccess file for my website having this code:

RewriteEngine on
RewriteBase /

RewriteRule ^bit_auth\/?(.*)$ /cig/base3/auth/$1 [R=301,NC,L]
RewriteCond $1 !^(index\.php|images|robots\.txt|assets|themes|includes)
RewriteRule ^(.*)$ /cig/base3/index.php/$1 [L]

I want to keep my site root path in a variable like this:

RewriteEngine on
RewriteBase /
SetEnv BASE_PATH "/cig/base3"

RewriteRule ^bit_auth\/?(.*)$ %{ENV:BASE_PATH}/auth/$1 [R=301,NC,L]
RewriteCond $1 !^(index\.php|images|robots\.txt|assets|themes|includes)
RewriteRule ^(.*)$ %{ENV:BASE_PATH}/index.php/$1 [L]

because I may need to use BASE_PATH value in more codes later and also it may be changed and I don't want to search and replace every time in my htaccess file. But when I use code above, in htaccess file %{ENV:BASE_PATH} is returning an empty value rather than expected /cig/base3 but in php when I call it using:

<?php $specialPath = getenv('BASE_PATH'); var_dump($specialPath)?>

it is showing the correct value of /cig/base3.

Whats the problem in my codes and how can I solve this?

like image 398
Mojtaba Rezaeian Avatar asked May 22 '15 14:05

Mojtaba Rezaeian


1 Answers

You can't use SetEnv that way because it's not processed yet.

The internal environment variables set by this directive are set after most early request processing directives are run, such as access control and URI-to-filename mapping. If the environment variable you're setting is meant as input into this early phase of processing such as the RewriteRule directive, you should instead set the environment variable with SetEnvIf.

What you are looking for is setenvif instead of SetEnv

So you should be able do something like

SetEnvIf Request_URI "^.*" base_path=/cig/base3

http://httpd.apache.org/docs/2.2/mod/mod_setenvif.html#setenvif

like image 100
Panama Jack Avatar answered Sep 24 '22 21:09

Panama Jack