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

Block/allow access to certain PHP pages

· 52CE 我爱测

I have a number of PHP scripts that are meant to be included into other PHP scripts, but otherwise should not be directly accessible to anyone via a Web browser. How do I block people from accessing these files directly over the …

问题原文

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

I have a number of PHP scripts that are meant to be included into other PHP scripts, but otherwise should not be directly accessible to anyone via a Web browser. How do I block people from accessing these files directly over the Internet? Is this possible using htaccess? Would it be better to put all these scripts into a sub-folder first? Also, what is the correct HTTP error/status code to display to visitors in this case?

已采纳解答

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

Would it be better to put all these scripts into a sub-folder first?

Yes. Then create a .htaccess file in that subdirectory with the following (mod_authz_core) directive:

Require all denied

(Assumes Apache 2.4+)

This will return a 403 Forbidden response for anyone trying to access anything inside that subdirectory.

Even better, put these PHP "includes" outside of the document root and they are inherently protected from direct access without doing anything else.

UPDATE: There are a handful of files that I may want people to access

In that case, you can use negative lookaheads (regex) in a <FilesMatch> container to create exceptions for the files you wish to allow access.

For example:

<FilesMatch "^(?!(foo|bar|baz)\.php$).+$">
Require all denied
</FilesMatch>

All files, except for foo.php, bar.php and baz.php will be blocked. (?!...) is a negative lookahead assertion, so whatever regex is contained in this (ie. (foo|bar|baz)\.php$) cannot match for the expression as a whole to be successful.

UPDATE#2: Checked my server and Apache Version 2.2.23

If you are still on Apache 2.2 (EOL January 2018) then you will need to change the Require all denied directive with the following:

Order deny,allow
Deny from all

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

资料来源与适用范围

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

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

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