Nginx限制访问

Nginx限制访问,nginx,Nginx,我有一个在nginx上运行的网站,我希望只允许其某些部分使用私有IP,其他部分使用私有和公共IP,例如: ww.mydomain.com/first-仅允许私人IP ww.mydomain.com/second-允许私人和公共IP 我尝试了许多选项,目前我有以下配置,但它同时阻止了公共和私有: location ^~/first { allow 172.0.0.0/24; deny all; return 404; } 谢谢。如果您试图限制对静态文件的访问,则问题可能是由try_files$u

我有一个在nginx上运行的网站,我希望只允许其某些部分使用私有IP,其他部分使用私有和公共IP,例如:

ww.mydomain.com/first-仅允许私人IP ww.mydomain.com/second-允许私人和公共IP

我尝试了许多选项,目前我有以下配置,但它同时阻止了公共和私有:

location ^~/first {
allow 172.0.0.0/24;
deny all;
return 404;
}

谢谢。

如果您试图限制对静态文件的访问,则问题可能是由
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/\u优先
403禁止
403禁止

nginx/1.1.19
它对我不起作用。我试图限制对/first-first的访问,但即使我离开位置^~/first/empty,我也得到了404,我还使用allow-all对其进行了测试,得到了相同的响应404,即使在remove-return 404时也是如此。我无法理解。@HSC查看更新的答案。不需要重写,这只是为了演示稍微复杂一点的场景。如果它太令人困惑,我可以删除它。
$ 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>