Nginx重定向反向代理404

Nginx redirect reverse proxy 404

我有以下 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/;
    }
}

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

但是,这个服务器块和 http://localhost 的服务器块都具有相同的 root,所以它也可以在内部指向 /example-404/,我不确定哪个更容易去做。无论哪种方式,我都希望浏览器地址栏中的地址保持不变。

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

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

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;
    }
}