简体   繁体   中英

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM