Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
787 views
in Technique[技术] by (71.8m points)

php - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...