当某些文件不存在时.htaccess重定向到404页面 [英] .Htaccess redirect to 404 page when certain files doesn't exist

查看:65
本文介绍了当某些文件不存在时.htaccess重定向到404页面的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经使用我自己的MVC系统一段时间了,并且效果很好!

I've been working with my own MVC system for a while now and it works great!

我在.htaccess中使用它

I use this in my .htaccess

RewriteEngine On

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

RewriteRule ^(.+)$ index.php?page=$1 [QSA,L]

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

Now, when a page (controller) doesn't exist, I redirect to /error (in the index.php file). But there are some scenarios when a picture will be deleted in a folder, and still be printed in the html page. This will automatically make the browsers call the picture, which doesn't exist (So it will call the /error page)

现在我想做的是,当图片或任何文件(我猜是php,html文件除外)时,我想重定向到404文件而不是/error.

Now what I want to do is that, when a picture, or any file, (except, php,html files i guess) I would like to redirect to a 404 file instead of the /error.

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

I am certain that this could be solved in the .htaccess file, but me and Apache aren't so buddies at the moment. Anyone who is friend with Apache?

谢谢!

推荐答案

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

Assuming that your images are in a common subfolder, for example /images in http://example.com/images/img.png, you can alter your rule to exclude this subdirectory completely, then add an errordocument. This .htaccess should be in your www-root.

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

请参见

  • Documentation for ErrorDocument
  • Documentation for mod_rewrite
  • Free friendship coupon for Apache (might or might not be expired)

这篇关于当某些文件不存在时.htaccess重定向到404页面的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆