Nginx重定向反向代理404错误。

3
我有以下的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页面。我真的很感激任何人对此的想法!
1个回答

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

虽然我不确定指定根目录 /usr/share/nginx/html 的目的是什么;但如果你正在使用 proxy_pass ... - DMCoding

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接