如何在 Nginx 中允许特定 IP 的 URL(不是目录!)

Lar*_*ars 6 nginx web-server

我试图拒绝访问我们在 Nginx 上运行的网站上的特定 URL,但允许从特定 IP 访问它,我一直在尝试使用 Location 摆弄,但似乎只是试图找到一个正确的目录而不是 URL。

这是我想出的,但只是返回了 404。

location /specificurl {
       root /var/www/site1.com/current;
       allow 123.123.123.123;
       deny all;
       }
Run Code Online (Sandbox Code Playgroud)

cad*_*dmi 5

您正在尝试为所有 IP 返回 404 错误,但指定的?使用带有“=404”参数的指令“error_page”。有点 ...

location /specificurl {
   root /var/www/site1.com/current;
   allow 123.123.123.123;
   deny all;

   error_page 403 =404 /404.html;

}
Run Code Online (Sandbox Code Playgroud)

http://nginx.org/en/docs/http/ngx_http_core_module.html#error_page

此外,可以将响应代码更改为 another,例如:

error_page 404 =200 /empty.gif;
Run Code Online (Sandbox Code Playgroud)

或者类似...

location /specificurl {
   root /var/www/site1.com/current;
   allow 123.123.123.123;
   deny all;

   error_page 403 = @goaway;

}

location @goaway {
    return 444;
}
Run Code Online (Sandbox Code Playgroud)


Lar*_*ars 4

我自己设法解决了这个问题,方法如下:

    set $deny_access off;

    if ($remote_addr !~ (123.123.123)) {
            set $deny_access on;
    }
    if ($uri ~ "^/(specificurl)$" ) {
            set $deny_access on$deny_access;
    }
    if ($deny_access = onon) {
            return 444;
    }
Run Code Online (Sandbox Code Playgroud)