使用 mod_rewrite 重定向到 Apache 内置 404 页面?
有没有办法使用 mod_rewrite 为多个 URL 主动提供 Apache 的默认内置 404 页面?不是自定义错误文档,而是像
RewriteCond %{REQUEST_URI} ^/dirname/pagename
RewriteRule -- serve 404 page -----
我知道如何构建发送 404 标头的 PHP 页面并让 mod_rewrite
重定向所有 URL 的规则,但我更喜欢基于 mod_rewrite
。
我只是想重定向到一个不存在的地址:
RewriteCond %{REQUEST_URI} ^/dirname/pagename
RewriteRule .* /sflkadsölfkasdfölkasdflökasdf
但这会在错误页面上向用户显示消息“/sflkadsölfkasdfölkasdflökasdf不存在”,这看起来有点不专业。
Is there a way to actively serve Apache's default, built-in 404 page for a number of URLs using mod_rewrite? Not a custom error document, but a rule like
RewriteCond %{REQUEST_URI} ^/dirname/pagename
RewriteRule -- serve 404 page -----
I know how to build a PHP page that sends the 404 header and have mod_rewrite
redirect all the URLs there but I would prefer a solution that is based on mod_rewrite
only.
I just had the idea of redirecting to a non-existent address:
RewriteCond %{REQUEST_URI} ^/dirname/pagename
RewriteRule .* /sflkadsölfkasdfölkasdflökasdf
but that would give the user the message "/sflkadsölfkasdfölkasdflökasdf does not exist" on the error page, which looks a bit unprofessional.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您可以在
RewriteRule
使用给定的状态代码强制重定向:因此:
将返回
/page.html
的默认 404 页面。由于这是一个正则表达式,请记住转义\.
和锚定$
。-
被忽略(即“替换字符串被删除”),但仍然需要有一些东西来保持规则的格式良好。You can use the
R
flag on theRewriteRule
to force a redirect with a given status code:So this:
would return the default 404 page for
/page.html
. Since this is a regexp, remember the escaping\.
and anchoring$
.-
is ignored (i.e. "the Substitution string is dropped"), but there still needs to be something there to keep the rule well-formed.最好的方法是使用状态代码 404 设置 R 标志:
但这仅从 Apache 2 开始可用。
The best way to do that is to set the R flag with the status code 404:
But this is only available since Apache 2.
我确认这一点
,否则
行不通。以下是Apache官方网站的解释:
因此,最好的解决方案是重定向到带有 404 标头的 404.php 文件,如下所述。
I confirm that
or
won't work. Here is the explanation from the official Apache website:
So the best solution is to redirect to a 404.php file with the 404 header as explained later.
这应该可行:
但不会给出 404 标头。您可以尝试更改标记为
[L,R=404]
但我怀疑这是否有效(它应该仅用于重定向)。您在 PHP 中这样做的想法是可行的。如果所有“错误页面”页面都是服务器端(即 PHP),那么您可以简单地使用以下代码:
This should work:
That won't give the 404 header though. You could try chaning to flag to
[L,R=404]
but I doubt that will work (it's supposed to be for redirects only).Your idea of doing so in PHP would work. If all your "error pages" pages are server-side (i.e. PHP) then you could simply use this code: