如何在.htaccess文件中定义变量并使用它? [英] how can I define variable in .htaccess file and use it?

查看:121
本文介绍了如何在.htaccess文件中定义变量并使用它?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我为我的网站定义了一个htaccess文件,其代码如下:

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]

我想将我的网站根路径保留在变量中,如下所示:

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]

因为稍后可能需要在更多代码中使用BASE_PATH值,并且可能会对其进行更改,因此我不想每次都在htaccess文件中进行搜索和替换. 但是,当我使用上述代码时,htaccess文件%{ENV:BASE_PATH}中的返回空值,而不是预期的/cig/base3 ,但是在php中,当我使用以下命令调用时:

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

它显示/cig/base3的正确值.

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

我的代码有什么问题,我该如何解决?

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

推荐答案

您不能以这种方式使用SetEnv,因为尚未对其进行处理.

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

此指令设置的内部环境变量在之后设置 大多数早期的请求处理指令都在运行,例如访问 控制和URI到文件名的映射.如果环境变量 您要设置的内容是该处理的早期阶段的输入 例如RewriteRule指令,您应该改为设置 带有SetEnvIf的环境变量.

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.

您要查找的是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

这篇关于如何在.htaccess文件中定义变量并使用它?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆