大网数据广告活动
网站运营与故障问答

Apache redirect all requests for file type to 404

· 52CE 我爱测

I have some .inc files that I want blocked from being accessible via web pages. I want to simply redirect them to another page or throw a 404 when those files are accessed. I have tried this so far which does not restrict anythin…

问题原文

原帖链接 · another_stack_user999 · CC BY-SA 4.0

I have some .inc files that I want blocked from being accessible via web pages. I want to simply redirect them to another page or throw a 404 when those files are accessed.

I have tried this so far which does not restrict anything:

RewriteCond %{REQUEST_URI} .*\.(inc)
RewriteRule ^(.*)/ /logout.php [R=404,L]

How can I block access to all files with the extension ".inc"

已采纳解答

原帖链接 · MrWhite · CC BY-SA 4.0

The usual way to "block" access to these files would be to serve a 403 Forbidden.

For example, using mod_authz_core on Apache 2.4:

<Files "*.inc">
    Require all denied
</Files>

If you specifically want to respond with a 404 instead then you can use mod_rewrite. This needs to go near the top of your config file. For example:

RewriteEngine On

RewriteRule \.inc$ - [R=404]

Both of these rules will result in the 403 or 404 error document being returned, which you can customise using the ErrorDocument directive. For example:

ErrorDocument 404 /errors/my404.html

Just a few notes on your code sample:

RewriteCond %{REQUEST_URI} .*\.(inc)
RewriteRule ^(.*)/ /logout.php [R=404,L]

This might have "worked", however, the RewriteRule pattern (ie. ^(.*)/) requires the URL to have contained a slash, which isn't the case for any files in the document root.

This also matches .inc anywhere inside the URL. The RewriteCond directive is not required here - you can do all the pattern matching in the RewriteRule directive.

There is no need for the capturing subpatterns, ie. the parentheses around (.*) and (inc). This creates "backreferences" which are not being used here.

When you specify a "redirect" code other than 3xx then the substitution string (ie. /logout.php) is ignored. No external redirect is triggered. You should just specify a single - (hyphen) in this case. Also, the L (last) flag is not required.


Aside: It's not a good idea to have files with the extension .inc if they are include/script files for your project (unless perhaps they are kept outside of your document root). As you may have realised, if requested directly, the browser will likely see them as text/plain and simply display them as-is in the browser. It is advisable to always use the correct script extension if possible. eg. foo.inc.php.

摘自公开归档,保留原文语言,版式经整理,外部媒体与邮箱地址已移除。

资料来源与适用范围

资料来源
Webmasters Stack Exchange
适用范围
以原帖系统、软件版本与发布日期为准(2019-10-28)
内容语言
中文;命令、路径和错误标识保留技术原文
本地收录日期
2026-11-15
授权说明
CC BY-SA 4.0

正文与所需资源由本站本地存储。查看来源及更新记录 ↗

请按适用版本和实际日志确认原因;本站没有对每一种系统或设备逐项执行文中的操作。