.htaccess 当某些文件不存在时重定向到 404 页面

Kil*_*ise 3 apache .htaccess mod-rewrite redirect http-status-code-404

我使用自己的 MVC 系统已经有一段时间了,它运行得很好!

我在我的 .htaccess 中使用它

RewriteEngine On

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

RewriteRule ^(.+)$ index.php?page=$1 [QSA,L]
Run Code Online (Sandbox Code Playgroud)

现在,当页面(控制器)不存在时,我重定向到 /error (在 index.php 文件中)。但有些情况下,文件夹中的图片会被删除,但仍会打印在html页面中。这将自动使浏览器调用不存在的图片(因此它将调用/error页面)

现在我想做的是,当一张图片或任何文件(我猜除了 php、html 文件)我想重定向到 404 文件而不是 /error。

我确信这个问题可以在 .htaccess 文件中解决,但我和 Apache 目前还不是那么好。有谁是 Apache 的朋友吗?

谢谢!

Sum*_*ai8 5

假设您的图像位于公共子文件夹中,例如/images在 中http://example.com/images/img.png,您可以更改规则以完全排除该子目录,然后添加错误文档。该 .htaccess 应该位于您的 www 根目录中。

RewriteEngine On

#If the file does not exist, and the url doesn't start with /images
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-l
RewriteCond %{REQUEST_URI} !^/images
RewriteRule ^(.+)$ index.php?page=$1 [QSA,L]

#If the rule above didn't match, and the file does not exist, use the ErrorDocument
ErrorDocument 404 /404.php
Run Code Online (Sandbox Code Playgroud)