使用 .htaccess 文件和 php 抛出 404 错误

throw 404 error with .htaccess file and php

我有 url 像 www.web.com/homewww.web.com/about 以及 .htaccess 文件:

RewriteEngine On
Options +FollowSymLinks
ErrorDocument 404 http://www.web.com/page-not-found.html
RewriteRule "home" "index.php?c=home&m=main"
RewriteRule "about" "index.php?c=home&m=about"

如果我输入类似 www.web.com/asd 的内容,.htaccess 将抛出 404 error 并直接 page-not-found.html file

但是,如果我键入 www.web.com/homessswww.web.com/about/a/b/c.htaccess 不会 抛出 404 error

我该如何解决?我用纯PHP

在重写规则中使用元字符 1:1 匹配:

^ --- 匹配输入的开头

$ --- 匹配输入的结尾

[L] --- 匹配后停止处理规则的标志

RewriteEngine On
Options +FollowSymLinks

ErrorDocument 404 http://www.web.com/page-not-found.html

RewriteRule ^home$ index.php?c=home&m=main [L]
RewriteRule ^about$ index.php?c=home&m=about [L]

除了...

If I type something like www.web.com/asd, .htaccess will throw 404 error

不是您发布的代码...

ErrorDocument 404 http://www.web.com/page-not-found.html

当请求未映射到资源时,上述触发 302(临时)重定向到 http://www.web.com/page-not-found.html。没有 404 HTTP 响应。触发响应的请求的详细信息丢失。 /page-not-found.html 暴露给最终用户。这通常不利于 SEO 并提供糟糕的用户体验。

ErrorDocument 指令的第二个参数应该是相对于根目录的 URL 路径,以斜杠开头,以便使用内部子请求调用错误文档。 Apache 然后以 404 状态响应。错误文档不会暴露给最终用户。

(这里很少使用绝对 URL。)

比如应该是这样的:

ErrorDocument 404 /page-not-found.html

参考: