Nginx 重定向反向代理 404

Zak*_*Zak 3 error-handling proxy reverse-proxy nginx vhosts

我有以下 Nginx 服务器块:

server {
    listen 80;
    listen [::]:80;
    server_name example.com;
    root /usr/share/nginx/html;

    location / {
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $remote_addr;
        proxy_pass http://localhost/page-1/;
    }
}
Run Code Online (Sandbox Code Playgroud)

我希望当用户在 example.com 上收到 404 错误时,proxy_pass应该更改为直接访问http://localhost/example-404/.

然而,这个服务器块和两者的服务器块http://localhost具有相同的root,所以或者它可以只指向/example-404/内部,我不确定哪个更容易做到。不管怎样,我希望浏览器地址栏中的地址保持不变。

我想要这个的原因是如果http://localhost直接访问服务器将会有一个不同的404页面。我真的很感激任何人对此的想法!

DMC*_*ing 6

您可以使用不同的虚拟主机来根据用户访问服务器的方式提供不同的结果。我想这样的事情可能会起作用:

server {
    listen 80;
    server_name example.com;
    root /usr/share/nginx/html;

    location / {
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $remote_addr;
        proxy_intercept_errors on;
        error_page 404 = @errors;
        proxy_pass http://localhost/page-1/;
    }
    location @errors {
        root /usr/share/nginx/errors/example.com.404.html;
    }
}

server {
    listen 80;
    server_name localhost;
    root /usr/share/nginx/html;

    location / {
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $remote_addr;
        proxy_intercept_errors on;
        error_page 404 = @errors;
        proxy_pass http://localhost/page-1/;
    }
    location @errors {
        root /usr/share/nginx/errors/localhost.404.html;
    }
}
Run Code Online (Sandbox Code Playgroud)