大网数据广告活动
服务器运维问答

How to use local error_page when remote error_page not found?

· 52CE 我爱测

I'm trying to create a fallback for my error_page. Basically, the logic should be something like the following: load foobar.html does not exist on remote server -> load 404.html from remote server to show 404 page does not exist …

问题原文

原帖链接 · Prisoner · CC BY-SA 4.0

I'm trying to create a fallback for my error_page. Basically, the logic should be something like the following:

  1. load foobar.html
  2. does not exist on remote server -> load 404.html from remote server to show 404 page
  3. does not exist on remote server -> load 404.html on local filesystem

Loading both localhost/404.html and localhost/global404.html works, but when I break localhost/404.html (by removing the file from the http server) it does not show the global404.html page as I'd expect.

server {
    listen 80;
    server_name example.com www.example.com;
    proxy_intercept_errors on;

    location / {
        proxy_pass http://localhost:3000;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $remote_addr;
        error_page 404 /404.html;
    }

    location /404.html {
        proxy_pass http://localhost:3000/404.html;
        error_page 404 /global404.html;
    }

    location /global404.html {
        root /usr/share/nginx/html;
    }
}

The above works fine when I hit http://localhost/404.html (when the 404.html file is on the remote server it shows that, when I delete the file it loads the global404.html file).

However, when I type a non-existent page I just get the default nginx 404 page.

已采纳解答

原帖链接 · Prisoner · CC BY-SA 4.0

Thanks to the wording of a comment left on the question, I managed to find the recursive_error_pages option which allows cascading/recursive error_pages. I feel stupid for missing it in the documentation.

But, simply doing

server {
    listen      80;
    server_name example.com www.example.com;
    proxy_intercept_errors on;
    recursive_error_pages on;

    location / {
        proxy_pass http://localhost:3000;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $remote_addr;
        error_page 404 /404.html;
    }

    location /404.html {
        proxy_pass http://localhost:3000/404.html;
        error_page 404 /global404.html;
    }

    location /global404.html {
        root /usr/share/nginx/html;
    }
}

worked a charm. I love nginx.

摘自公开归档,保留原文语言,版式经整理,外部媒体与邮箱地址已移除。

资料来源与适用范围

资料来源
Server Fault
适用范围
以原帖系统、软件版本与发布日期为准(2020-05-17)
内容语言
中文;命令、路径和错误标识保留技术原文
本地收录日期
2026-11-15
授权说明
CC BY-SA 4.0

正文与所需资源由本站本地存储。查看来源及更新记录 ↗

请按适用版本和实际日志确认原因;本站没有对每一种系统或设备逐项执行文中的操作。