简体   繁体   English

如何在.htaccess文件中定义变量并使用它?

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

I have defined an htaccess file for my website having this code: 我为我的网站定义了一个htaccess文件,其代码如下:

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. 因为我以后可能需要在更多代码中使用BASE_PATH值,并且可能会对其进行更改,所以我不想每次都在htaccess文件中进行搜索和替换。 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: 但是,当我使用上面的代码时, 在htaccess文件中, %{ENV:BASE_PATH}返回的是空值,而不是预期的/cig/base3但是在php中,当我使用以下代码调用它时:

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

it is showing the correct value of /cig/base3 . 它显示/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. 您不能以这种方式使用SetEnv ,因为尚未处理它。

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. 此指令设置的内部环境变量是在大多数早期请求处理指令运行后设置的,例如访问控制和URI到文件名的映射。 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. 如果要设置的环境变量是该处理的早期阶段的输入(例如RewriteRule指令),则应改为使用SetEnvIf设置环境变量。

What you are looking for is setenvif instead of SetEnv 你所寻找的是setenvif ,而不是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 http://httpd.apache.org/docs/2.2/mod/mod_setenvif.html#setenvif

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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