Nginx won't use custom 502 error page

允我心安 提交于 2020-01-17 05:16:21

问题


I am trying to display a custom 502 error page when webserver behind (upstream) is offline, but it doesn't work : it continues displaying default 502 error page (and I'm sure upstream is offline).

My file organization is the following :

  • Static files are under /var/web/example.org/www/res (example: /var/web/example.org/www/res/robots.txt) ;
  • Error pages are under /var/web/example.org/www (example: /var/web/example.org/www/502.html). This is because i don't want error pages (not coming from the webserver behind, including 404 and others) to be accessible when that webserver is on.

Here is my (anonymised) config :

upstream exampleorg {
        server 127.0.0.1:8087;
}
server {
    listen 80;
    server_name www.example.org;

    # content
    # - static
    root /var/web/example.org/www/res;

    # - main webserver
    error_page 403 404 @exampleorg;
    error_page 502 /../502.html;
    location @exampleorg {
        proxy_pass http://exampleorg;
        proxy_redirect off;

        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
    }
}

I have also tried the following to define the following for catching the 502 (in the server block, at the end) :

error_page 502 /502.html;
location /502.html {
    root /var/web/example.org/www;
    internal;
}

But nginx continued displaying default 502 page (even without the internal;). How should I do ? Thanks in advance for your solution(s) :)


回答1:


Found the solution after some experimenting. I think the error came from the "error_page" 404 statements, and I didn't think try_files was so powerful. Anyway, that's the final configuration that works, as it can be useful to some people :

upstream exampleorg {
        server 127.0.0.1:8087;
}
server {
    listen 80;
    server_name www.example.org;

    # content
    # - static
    location / {
        root /var/web/example.org/www/res;
        try_files $uri @exampleorg;
    }

    # - main webserver
    location @exampleorg {
        proxy_pass http://exampleorg;
        proxy_redirect off;

        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
    }

    # - error
    error_page 502 @offline;
    location @offline {
        root /var/web/example.org/www;
        try_files /502.html 502;
    }
}


来源:https://stackoverflow.com/questions/38158585/nginx-wont-use-custom-502-error-page

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!