如果你想限制訪問靜態文件,該問題可能是由try_files $uri =404
(默認)引起的,如果文件存在於特定地點可能匹配。下面的例子可能看起來過於複雜,但展示了nginx的功能,應該是非常防彈的。
我假設以下目錄結構:
/var/www/
├── chroot
├── _first
│ └── index.html
├── index.html
└── _second
└── index.html
和站點配置:
# proxy server for accessing real files
server {
listen 8080;
index index.html index.htm;
server_name _;
root /var/www;
try_files $uri $uri/ =404;
}
server {
listen 80;
index index.html index.htm;
server_name _;
root /var/www/chroot; # empty jail directory
try_files index.htm =404; # non-existing location
location ^~ /first {
# in case that $uri exists, deny rule is not applied
allow 127.0.0.1/32;
deny all;
try_files $uri @proxy;
}
location @proxy {
rewrite ^/first(.*)$ /_first/$1 break;
proxy_pass http://127.0.0.1:8080;
proxy_redirect off;
proxy_set_header Host $host;
}
location ^~ /second {
rewrite ^/second(.*)$ /_second/$1 break;
proxy_pass http://127.0.0.1:8080;
proxy_redirect off;
proxy_set_header Host $host;
}
# shoud match all not above
location/{
deny all;
return 403;
}
}
現在一些基本的測試,當你從許可IP訪問:
$ curl -L localhost:80/first
first
公共端點
$ curl -L localhost:80/second
second
任何其他URI應該導致403
,喜歡嘗試訪問「私人」的URI:
$ curl -L localhost:80/_first
<html>
<head><title>403 Forbidden</title></head>
<body bgcolor="white">
<center><h1>403 Forbidden</h1></center>
<hr><center>nginx/1.1.19</center>
</body>
</html>
這不是爲我工作。我試圖限制訪問/首先,但即使當我離開的位置^〜/第一/空我得到404,我也測試了所有允許我得到相同的響應404,即使刪除返回404。無法弄清楚這一點。 – HSC
@HSC查看更新後的答案。重寫不是必要的,只是爲了演示稍微複雜的場景。如果太混亂,我可以刪除它。 – Tombart