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

查看:29
本文介绍了如何在 .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

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

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

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