Apache 的 mod_rewrite 和 %{REQUEST_URI} 问题
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1217413/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Apache's mod_rewrite and %{REQUEST_URI} problem
提问by liviucmg
suppose we have the following PHP page "index.php":
假设我们有以下 PHP 页面“index.php”:
<?
if (!isset($_GET['req'])) $_GET['req'] = "null";
echo $_SERVER['REQUEST_URI'] . "<br>" . $_GET['req'];
?>
and the following ".htaccess" file:
以及以下“.htaccess”文件:
RewriteRule ^2.php$ index.php?req=%{REQUEST_URI}
RewriteRule ^1.php$ 2.php
Now, let's access "index.php". We get this:
现在,让我们访问“index.php”。我们得到这个:
/index.php
null
That's cool. Let's access "2.php". We get this:
这很酷。让我们访问“2.php”。我们得到这个:
/2.php
/2.php
That's cool too. But now let's have a look at "1.php":
这也很酷。但是现在让我们看看“1.php”:
/1.php
/2.php
So... we ask for "1.php", it silently redirects to "2.php" which silently redirects to "index.php?req=%{REQUEST_URI}", but here the "%{REQUEST_URI}" seems to be "2.php" (the page we're looking for afterthe first redirection) and the $_SERVER['REQUEST_URI'] is "1.php" (the original request).
所以......我们要求“1.php”,它默默地重定向到“2.php”,默默地重定向到“index.php?req=%{REQUEST_URI}”,但这里的“%{REQUEST_URI}”似乎是“2.php”(我们在第一次重定向后寻找的页面),而 $_SERVER['REQUEST_URI'] 是“1.php”(原始请求)。
Shouldn't these variables be equal? This gave me a lot of headaches today as I was trying to do a redirection based only on the originalrequest. Is there any variable I can use in ".htaccess" that will tell me the original request even after a redirection?
这些变量不应该相等吗?这让我今天很头疼,因为我试图仅根据原始请求进行重定向。是否有任何我可以在“.htaccess”中使用的变量,即使在重定向后也会告诉我原始请求?
Thanks in advance and I hope I've made myself clear. It's my first post here :)
提前致谢,我希望我已经说清楚了。这是我在这里的第一篇文章:)
采纳答案by liviucmg
Well I guess I solved the problem. I used the %{THE_REQUEST} variable which basically contains something like this: "GET /123.php HTTP/1.1". It remains the same even after a redirection. Thanks everyone for your help! :)
好吧,我想我解决了这个问题。我使用了 %{THE_REQUEST} 变量,它基本上包含如下内容:“GET /123.php HTTP/1.1”。即使在重定向后它也保持不变。感谢大家的帮助!:)
回答by chaos
I'm not sure whether it will meet your needs, but try looking at REDIRECT_REQUEST_URIfirst, then if it's not there, REQUEST_URI. You mention in your comment to Gumbo's answer that what you're truly looking for is the original URI; REDIRECT_*versions of server variables are how Apache tries to make that sort of thing available.
我不确定它是否会满足您的需求,但请先尝试查看REDIRECT_REQUEST_URI,如果不存在,则REQUEST_URI. 您在对 Gumbo 的回答的评论中提到,您真正要寻找的是原始 URI;REDIRECT_*服务器变量的版本是 Apache 试图使这种事情可用的方式。
回答by Gumbo
Just change the order of the rules and it works:
只需更改规则的顺序即可:
RewriteRule ^1\.php$ 2.php
RewriteRule ^2\.php$ index.php?req=%{REQUEST_URI}
Or use just one rule:
或者只使用一个规则:
RewriteRule ^(1|2)\.php$ index.php?req=%{REQUEST_URI}

