如何在nginx上拒绝使用404

Dmi*_*mov 7 security nginx http-status-code-403 http-status-code-404

我想通过提供deny/allow指令来保护nginx中的某些位置,但我不希望局外人知道位置被拒绝.我希望局外人获得404,而不是403 http代码.我的配置代码段是

location /admin/ {
    uwsgi_pass myupstream1;
    include /path/to/uwsgi_params;

    allow 127.0.0.1;
    deny all;
}
Run Code Online (Sandbox Code Playgroud)

当我尝试访问/ admin/nginx使用HTTP 403响应时,但我希望它以HTTP 404响应.任何配方都可以吗?

小智 5

error_page 403 404 /404.html;

location = /404.html {
    internal; #return 404
}

location /admin/ {
    uwsgi_pass myupstream1;
    include /path/to/uwsgi_params;

    allow 127.0.0.1;
    deny all;
}
Run Code Online (Sandbox Code Playgroud)

默认情况下,“内部”返回404。

这里改编这个答案

  • 尽管此答案确实有效,但Nginx文档建议第一行应具有赋值运算符,即'error_page 403 = 404 /404.html;'。 (2认同)

dev*_*v0z 2

更优雅的方法是创建自定义错误页面。在该页面中,您可以指定自定义消息,而不是显示 http 错误代码。

命名错误页面

error_page 403 =404 /40X.html;

    location /admin/ {
        uwsgi_pass myupstream1;
        include /path/to/uwsgi_params;
        allow 127.0.0.1;
        deny all;  
    }

    location /40X.html {
    root path/to/public;
    }
Run Code Online (Sandbox Code Playgroud)

在你的 40x.html 中你可以写任何消息

<html>
<body> The requested resource is not available </body>
</html>
Run Code Online (Sandbox Code Playgroud)

将此 40x.html 放在您的 path/to/public 目录中