Apache htaccess 重定向所有 404(文件和文件夹)

Apache htaccess redirect all 404 (files and folders)

我想将所有“404”错误重定向到 PHP 文件。我使用 Wordpress 的 .htaccess 作为初始步骤。有效,但当路径是文件夹时无效,意思是末尾有一个“/”,我收到一个禁止的错误。

RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /includes/redir.php [L]

如果我尝试:

http://example.com/anything

按预期工作,重定向到我的 redir.php。但如果我尝试:

http://example.com/anything/

returns 一个禁止的错误。

我需要做什么才能重定向到 redir.php 不存在的所有内容? 我需要改变httpd.conf?我需要 "ErrorDocument 404 /includes/redir.php" 行吗?

I need a "ErrorDocument 404 /includes/redir.php" line?

是的,使用这样的 ErrorDocument 指令比尝试手动 redirect/rewrite 错误文档要好得多。

定义的 ErrorDocument 将 return 正确的 HTTP 状态代码(无需您手动执行此操作)。 PHP 将在 $_SERVER 超全局中设置与此错误相关的其他变量。


如果你特别想在 404 上重写一个文件,那么你可以这样做:

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^ /includes/redir.php [L]

but not when the path is a folder, means, had a "/" at end, I get a Forbidden error.

URL "looks" 是否像文件夹一样真的不重要,除非 URL 映射到磁盘上的物理文件夹。只有这样,如果没有目录索引文档,您才会得到 403 Forbidden。