.htaccess 重写规则防止无限循环

发布于 2024-09-06 19:02:18 字数 568 浏览 3 评论 0原文

我有一个名为 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

终难愈 2024-09-13 19:02:18

重写的常用解决方案是仅检查所请求的路径是否指向实际的文件/目录,如果没有则重写它 - 因为重写的 URL 将指向实际的文件,没有循环发生。

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d

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.

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
三寸金莲 2024-09-13 19:02:18

安布尔的回答应该会让事情对你有用,但我想解决你的具体案例中出现的问题。您的想法是正确的,但 %{REQUEST_FILENAME} 实际上最终成为这里的完全限定路径,因此您的正则表达式应该在末尾检查 index.php,而不是开始。

因此,您应该发现这将更像您期望的那样工作:

RewriteEngine On

RewriteCond %{REQUEST_FILENAME} !index\.php$
RewriteRule ^(.+)$ index.php?dollars=$1

不过,如果您向该目录添加了其他内容,则将 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 for index.php at the end, not the beginning.

Consequently, you should find that this will work more like you expect:

RewriteEngine On

RewriteCond %{REQUEST_FILENAME} !index\.php$
RewriteRule ^(.+)$ index.php?dollars=$1

Swapping out the RewriteConds 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文