且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

拒绝直接访问除 index.php 之外的所有 .php 文件

更新时间:2023-02-19 21:44:45

您确定要这样做吗?甚至 css 和 js 文件和图像和...?

Are you sure, you want to do that? Even css and js files and images and ...?

好的,首先检查apache中是否安装了mod_access,然后将以下内容添加到您的.htaccess中:

OK, first check if mod_access in installed to apache, then add the following to your .htaccess:

Order Deny,Allow
Deny from all
Allow from 127.0.0.1

<Files /index.php>
    Order Allow,Deny
    Allow from all
</Files>

第一个指令禁止访问除本地主机以外的任何文件,因为Order Deny,Allow,Allow 稍后应用,第二个指令只影响 index.php.

The first directive forbids access to any files except from localhost, because of Order Deny,Allow, Allow gets applied later, the second directive only affects index.php.

警告:订单行中逗号后没有空格.

Caveat: No space after the comma in the Order line.

要允许访问匹配 *.css 或 *.js 的文件,请使用以下指令:

To allow access to files matching *.css or *.js use this directive:

<FilesMatch ".*.(css|js)$">
    Order Allow,Deny
    Allow from all
</FilesMatch>

但是,您不能在 .htaccess 文件中使用 指令.

You cannot use directives for <Location> or <Directory> inside .htaccess files, though.

您的选择是在第一个允许、拒绝组周围使用 ,然后明确允许访问 index.php.

Your option would be to use <FilesMatch ".*.php$"> around the first allow,deny group and then explicitely allow access to index.php.

Apache 2.4 更新:这个答案对于 Apache 2.2 是正确的.在 Apache 2.4 中,访问控制范式发生了变化,正确的语法是使用 Require all denied.

Update for Apache 2.4: This answer is correct for Apache 2.2. In Apache 2.4 the access control paradigm has changed, and the correct syntax is to use Require all denied.