Nginx 拒绝对文件夹文件不起作用

Nginx 拒绝对文件夹文件不起作用

我试图限制对我网站的访问,只允许特定 IP 访问,但出现了以下问题:当我访问 www.example.com 时,拒绝功能运行正常,但当我尝试访问 www.example.com/index.php 时,它返回“拒绝访问”页面,并且 php 文件直接在浏览器中下载,没有经过处理。我确实想拒绝除我的 IP 之外的所有 IP 访问网站上的所有文件。我该怎么做?

这是我的配置:

server {
listen 80;
server_name example.com; 
root /var/www/example;

location / {
    index index.html index.php; ## Allow a static html file to be shown first
    try_files $uri $uri/ @handler; ## If missing pass the URI to front handler
    expires 30d; ## Assume all files are cachable
 allow my.public.ip;
 deny all;
}

location @handler { ## Common front handler
    rewrite / /index.php;
}
location ~ .php/ { ## Forward paths like /js/index.php/x.js to relevant handler
    rewrite ^(.*.php)/ $1 last;
}

location ~ .php$ { ## Execute PHP scripts
    if (!-e $request_filename) { rewrite / /index.php last; } ## Catch 404s that try_files miss

    expires        off; ## Do not cache dynamic content
    fastcgi_pass   127.0.0.1:9001;
    fastcgi_param  HTTPS $fastcgi_https;
    fastcgi_param  SCRIPT_FILENAME  $document_root$fastcgi_script_name;
    include        fastcgi_params; ## See /etc/nginx/fastcgi_params
    }
}

答案1

您的location @handler是完全不必要和多余的,并且可能是问题的原因。这已包含在您现有的indextry_files指令中。完全删除location并修复try_files

try_files $uri $uri/ /index.php;

答案2

好的,我找到了解决方案。Nginx 处理最精确的正则表达式,在本例中是 php 文件的正则表达式。要使配置正常工作,除 @handler 之外,所有其他位置都必须在 / 位置规则内定义(您不能将其置于任何规则之下 - 只能以 root 身份进行)

server {
listen 80;
server_name example.com; 
root /var/www/example;

    location / {
    index index.html index.php; ## Allow a static html file to be shown first
    try_files $uri $uri/ @handler; ## If missing pass the URI to front handler
    expires 30d; ## Assume all files are cachable
    allow my.public.ip;
    deny all;

    location ~ .php/ { ## Forward paths like /js/index.php/x.js to relevant handler
        rewrite ^(.*.php)/ $1 last;
    }

    location ~ .php$ { ## Execute PHP scripts
        if (!-e $request_filename) { rewrite / /index.php last; } ## Catch 404s that try_files miss

        expires        off; ## Do not cache dynamic content
        fastcgi_pass   127.0.0.1:9001;
        fastcgi_param  HTTPS $fastcgi_https;
        fastcgi_param  SCRIPT_FILENAME  $document_root$fastcgi_script_name;
        include        fastcgi_params; ## See /etc/nginx/fastcgi_params
        }
}

    location @handler { ## Common front handler
        rewrite / /index.php;
    }

}

相关内容