Nginx允许/拒绝被忽略的指令,php正在处理

我有一个目录(www / nginx / website1 / private),我不想通过networking浏览器访问,但是依赖于该目录内容的php应用程序必须访问该目录。

我尝试了所有我能想到的,并在这里阅读类似的问题。 没有我已经尝试过的工作。

我努力了:

location /private/ { allow 127.0.0.1; deny all; return 404; # do not want to acknowledge existence of files. return 404 } 

它不起作用。 如果我直接导​​航到php文件,它将处理php文件 – 我已经通过在php文件中添加一个echo命令来确认。

这是我目前的nginx.conf文件(没有任何失败的尝试)。 我需要添加(以及在哪里)以上述方式阻止访问?

非常感谢你!

 user www; worker_processes 4; error_log /var/log/nginx/error.log info; events { worker_connections 1024; } http { include mime.types; default_type application/octet-stream; # Set size for max uploaded content client_max_body_size 0; #max size disabled client_header_timeout 30m; client_body_timeout 30m; access_log /var/log/nginx/access.log; ## Block spammers ## include blockips.conf; sendfile on; keepalive_timeout 65; server { listen 80; server_name REDACTED; root /usr/local/www/nginx; index index.php index.html index.htm; listen 443 ssl; server_name REDACTED ssl_certificate REDACTED; ssl_certificate_key REDACTED; ssl_protocols TLSv1 TLSv1.1 TLSv1.2; ssl_ciphers HIGH:!aNULL:!MD5; ### case insensitive http user agent blocking ### if ($http_user_agent ~* (Googlebot|AdsBot-Google|Googlebot-images|msnbot|Bingbot|AltaVista|archive|archive.is|Slurp) ) { return 403; } ## Only allow these request methods ## if ($request_method !~ ^(GET|HEAD|POST)$ ) { return 444; } ## Do not accept DELETE, SEARCH and other methods ## location / { try_files $uri $uri/ =404; } error_page 500 502 503 504 /50x.html; location = /50x.html { root /usr/local/www/nginx-dist; } location ~ \.php$ { try_files $uri =404; fastcgi_split_path_info ^(.+\.php)(/.+)$; fastcgi_pass unix:/var/run/php-fpm.sock; fastcgi_index index.php; fastcgi_param SCRIPT_FILENAME $request_filename; include fastcgi_params; } } } 

正如location指令文档所指出的那样,正则expression式在尝试前缀匹配之后被匹配​​,正则expression式在这种情况下匹配win。

为了防止这种行为,必须在location块中使用^~修饰符。

所以,你的屏蔽规则应该是这样的:

 location ^~ /private/ { allow 127.0.0.1; deny all; location ~ \.php$ { try_files $uri =404; fastcgi_split_path_info ^(.+\.php)(/.+)$; fastcgi_pass unix:/var/run/php-fpm.sock; fastcgi_index index.php; fastcgi_param SCRIPT_FILENAME $request_filename; include fastcgi_params; } } 

我们还需要在这里复制PHP处理块,因为^~修饰符阻止使用主PHP块。

这里不能使用return ,否则总会返回403错误码。

如果你想要另一个错误代码,我想你唯一的select是在你的PHP脚本中实现访问控制。

编辑:根据阿列克谢的评论更新。