我想写一个简单的重写规则,将会改变:
https://example.com/index.php?shortened_url=value
至
https://example.com/value
为了达到这个目的,我使用了下面的重写规则:
RewriteEngine On RewriteRule ^([^/]*)$ /index.php?shortened_url=$1 [L]
但是我收到错误:
由于可能的configuration错误,请求超出了10个内部redirect的限制。
显然这表明有一个循环问题的地方,但据我所知,我的规则是非常简单的,不应该导致任何循环?
首先你错位了RewriteRule命令的参数,顺序是
RewriteRule WHAT WHERE [OPTIONS]
(简化事物的快捷方式 – 参考文档)
还有更多关于RewriteRule的地方http://httpd.apache.org/docs/current/mod/mod_rewrite.html
如果我没有弄错的话,你的规则实际上是在/index.php?shortened_url=$1
重写任意数量的斜杠。
所以你的https://example.com/
被redirect到长URL和https://example.com/////////
你需要刷新你的正则expression式技能 – 试试这个链接来帮助你https://regexr.com/
最后,你正在寻找的规则应该是这样的:
RewriteRule ^/index.php\?shortened_url=(.*)$ https://example.com/$1 [L]
RewriteRule ^([^/]*)$ /index.php?shortened_url=$1 [L]
这将导致重写循环,因为/index.php?shortened_url=value
将被进一步重写为/index.php?shortened_url=index.php
(一遍又一遍)。
防止这种重写循环的一种方法是只在没有查询string的情况下重写(假设您没有在该URL上使用查询string用于其他目的)。 例如:
RewriteCond %{QUERY_STRING) ^$ RewriteRule ^([^/]*)$ /index.php?shortened_url=$1 [L]
或者,从RewriteRule
模式中排除点。 例如:
RewriteRule ^([^/.]*)$ /index.php?shortened_url=$1 [L]
这里要注意的重要一点是,在每个目录.htaccess
文件中使用L
( last
)标志不会停止所有处理。 它只是停止当前的一轮处理。 重写过程有效地重新开始直到URL通过不变。 您需要防止重写的URL被进一步重写。
这将会改变:
https://example.com/index.php?shortened_url=value
至
https://example.com/value
bocian85当然有一个关于你的描述,因为你的代码是完全相反的。 您的代码会将https://example.com/value
重写为https://example.com/index.php?shortened_url=value
。 (推测你已经改变了你的应用程序中的urlhttps://example.com/value
?)
但是,代码看起来正在做正确的事情,所以我认为这只是你的描述。 (?)(好奇……人们经常会像你所做的那样描述这一点 – 按照相反的顺序 – 就好像它们是在应用程序中描述最终结果一样,而不是指令实际执行的内容)。