如何将除一个 URL 之外的所有 URL 重定向到脚本
我试图让 www.example.com 和 www.example.com/index.html 转到 index.html,但我希望所有其他网址(例如 www.example.com/this/is/another/link)仍然显示 www.example.com/this/is/another/link 但由通用脚本处理。我已经尝试过
RewriteEngine on
RewriteCond %{REQUEST_URI} !^index\.html$
RewriteCond %{REQUEST_URI} !^$
RewriteRule ^(.*)$ mygenericscript.php [L]
,但行不通,有人可以帮忙吗?
I'm trying to get www.example.com and www.example.com/index.html to go to index.html, but I want all other urls e.g. www.example.com/this/is/another/link to still show www.example.com/this/is/another/link but be processed by a generic script. I've tried
RewriteEngine on
RewriteCond %{REQUEST_URI} !^index\.html$
RewriteCond %{REQUEST_URI} !^$
RewriteRule ^(.*)$ mygenericscript.php [L]
but it wont work, can someone please help?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以只测试资源是否存在,而不是测试
%{REQUEST_URI}
是什么:这可以防止您的静态资源(图像、样式表等)在通过您的
.htaccess
也位于同一目录中。现在可能发生的情况是,当您尝试访问
/
或/index.html.这是因为
.*
匹配每个请求,并且在您第一次重写到mygenericscript.php
后,规则集将被重新处理(因为mod_rewrite
code> 在您使用它的上下文中工作)。Instead of testing what
%{REQUEST_URI}
is, you can instead just test if the resource exists:This prevents your static resources (images, stylesheets, etc.) from being redirected if they're handled through the same directory your
.htaccess
is in as well.What's probably happening now is that you're seeing an internal server error, caused by an infinite internal redirection loop when you try to access anything that isn't
/
or/index.html
. This is because.*
matches every request, and after you rewrite tomygenericscript.php
the first time, the rule set is reprocessed (because of howmod_rewrite
works in the context that you're using it in).最简单的方法是安装一个 404 处理程序,当服务器找不到要显示的文件时执行该处理程序。
或
类似的应该可以解决问题。
并不是说 RewriteRule 不能用于此目的,只是它们的设置比较棘手,并且需要深入了解 apache 如何处理请求。这有点像黑魔法。
The easiest to do this is to install a 404-handler which gets executed when the server does not find a file to display.
or
or similar should do the trick.
It is not that RewriteRule's can not be used for this, it is just that they are tricky to set up and requires in depth knowledge on how apache handles requests. It is a bit of a black art.
看起来好像您正在使用 PHP,并且可以使用 auto_x_file (x 是附加或前置:
http://php.net/manual/en/ini.core.php
It appears as if you're using PHP, and you can use auto_x_file (x is either append or prepend:
http://php.net/manual/en/ini.core.php