.htaccess 重写规则防止无限循环
我有一个名为 dollars 的目录,其中包含一个文件 index.php。我想要翻译网址 http://localhost/dollars/foo到dollars/index.php?dollars=foo。这是我当前在 dollars 目录中的 .htaccess 文件:
Options +FollowSymLinks
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !^index\.php
RewriteRule ^(.+)$ index.php?dollars=$1 [L]
其想法是,除了对 index.php 的请求之外的任何请求都应该使用 RewriteRule。
然而,这是行不通的。
我一直在寻找一段时间,试图弄清楚如何创建我想要的重定向,但我什至不知道我是否走在正确的轨道上。正则表达式从来都不是我的菜。感谢您的帮助!
I have a directory named dollars that contains a file index.php. I would like for the url http://localhost/dollars/foo to translate to dollars/index.php?dollars=foo. This is the .htaccess file that I currently have in the dollars directorty:
Options +FollowSymLinks
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !^index\.php
RewriteRule ^(.+)$ index.php?dollars=$1 [L]
The idea being that any request other than a request to index.php should use the RewriteRule.
However, this does not work.
I've been looking for a while trying to figure out how to create the redirect I want, but I don't even know if I'm on the right track. Regex were never my thing. Thanks for any help!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
重写的常用解决方案是仅检查所请求的路径是否指向实际的文件/目录,如果没有则重写它 - 因为重写的 URL 将指向实际的文件,没有循环发生。
A often-used solution for rewrites is to just check that the path being requested doesn't point to an actual file/directory, and rewrite it if it doesn't - since the rewritten URL will then point to an actual file, no loop occurs.
安布尔的回答应该会让事情对你有用,但我想解决你的具体案例中出现的问题。您的想法是正确的,但
%{REQUEST_FILENAME}
实际上最终成为这里的完全限定路径,因此您的正则表达式应该在末尾检查index.php
,而不是开始。因此,您应该发现这将更像您期望的那样工作:
不过,如果您向该目录添加了其他内容,则将
RewriteCond
替换为 Amber 提到的内容会减少问题,所以我会无论如何,建议使用它来代替它。Amber's answer should get things working for you, but I wanted to address what was going wrong in your specific case. You had the right idea, but
%{REQUEST_FILENAME}
actually ends up being a fully qualified path here, so your regular expression should check forindex.php
at the end, not the beginning.Consequently, you should find that this will work more like you expect:
Swapping out the
RewriteCond
s for those that Amber mentioned would be less problematic if you added other things to that directory, though, so I'd recommend using that in place of this anyway.