Nginx 阻止访问 PHP 文件

Nginx 阻止访问 PHP 文件

我尝试仅允许访问我的 index.php 文件并阻止所有其他 php 文件。但是,在 Windows 机器上可以正常工作,但在 Debian 上却遇到了麻烦。

# Route all requests for non-existent files to index.php
if (!-e $request_filename) {
    rewrite ^/(.*)$ /index.php/$1 last;
}

# Hide all PHP scripts
location ~ \.php {
    rewrite ^/(.*)$ /index.php/$1 last;
}

# Forward index.php requests to php-fastcgi
location ~ ^/index.php {
    include fastcgi_params;
    fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
    fastcgi_pass 127.0.0.1:9000;
}

目标是确保所有内容都通过索引,这样就没有人可以加载任何可通过网络访问的 php 类。

答案1

您不需要 if 检查。我还尝试稍微清理一下配置文件,以避免不必要的捕获和指令。我认为它应该可以工作,但它是自由编写的,因此可能会有语法错误等。

try_files $uri @missing;

location @missing {
    rewrite ^ /index.php$request_uri last;
}

# This will only run if the below location doesn't, so anything other than /index.php
location ~ \.php {
    rewrite ^ /index.php$request_uri last;
}

# Remove the = if it doesn't match because of the rewrite appending the URI.
location = /index.php {
    include fastcgi.conf; # Notice that I changed the file, 
    fastcgi_pass 127.0.0.1:9000;
}

相关内容