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

Make a file invisible remotely

· 52CE 我爱测

I have a PHP file that stores some connection info for part of my website. It is not "readable" from the Web, which is good. I.e. it is blank when you navigate to it from the Web. However, even if it is blank, I would rather the …

问题原文

原帖链接 · posfan12 · CC BY-SA 3.0

I have a PHP file that stores some connection info for part of my website. It is not "readable" from the Web, which is good. I.e. it is blank when you navigate to it from the Web.

However, even if it is blank, I would rather the server return an 403 error message when people navigate to it. Can I use .htaccess to make the server return this error? What is the proper way to do this?

社区高分解答

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

It is not "readable" from the Web

What you are seeing is the output after the PHP file has been processed. Since you are probably only setting some variables then there is no output, but it is still processed. If PHP should fail, or the file should get an error/corrupted then this could expose the PHP contents.

Ideally, you would simply put this file outside/above the document root. That way you don't have to do anything to block it from the public and will still be blocked should anything untoward happen (such as your .htaccess being accidentally deleted!).

To block this with mod_rewrite in .htaccess:

RewriteEngine On
RewriteRule ^file-to-block\.php$ - [F]

The above should be placed near the top of your .htaccess file.

Note, however, that if you include another .htaccess file in a subdirectory, that also uses mod_rewrite, then this directive could be overridden.


However, it would be preferable to block (403) these files with mod_authz_host (Apache 2.2) or mod_authz_core (Apache 2.4). For Apache 2.2 see Simon's answer.

On Apache 2.4, using mod_authz_core:

<Files "file-to-block.php">
    Require all denied
</Files>

Alternatively, to send a 404 Not Found instead of a 403 Forbidden, then you can modify the above mod_rewrite directive:

RewriteRule ^file-to-block\.php$ - [R=404,L]

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

资料来源与适用范围

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

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

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