Nginx won't use custom 502 error page

2019-08-27 08:06发布

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条回答
ら.Afraid
2楼-- · 2019-08-27 09:08

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;
    }
}
查看更多
登录 后发表回答