.Htaccess redirect to 404 page when certain files doesn't exist

混江龙づ霸主 提交于 2021-02-10 07:15:41

问题


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

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]

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)

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.

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?

Thanks!


回答1:


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

See

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


来源:https://stackoverflow.com/questions/25097624/htaccess-redirect-to-404-page-when-certain-files-doesnt-exist

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!