reverse proxy – Chaining multiple nginx error pages

I’m fighting a bit with nginx and try to get a “chain” of nginx error pages to work. Current state looks like this:

server {
    listen       443 ssl;
    server_name  ~^((?<repo>.*).)$;

    ssl_certificate /etc/pki/tls/certs/cert.pem;
    ssl_certificate_key /etc/pki/tls/private/key.pem;
    client_max_body_size 100M;

    location / {
        proxy_pass http://backend_example/example/${repo}$request_uri;
        proxy_http_version 1.1;
        proxy_buffering off;
        proxy_connect_timeout 300;
        proxy_intercept_errors on;

        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;
        proxy_redirect off;

        rewrite  ^/$  /index.html  permanent;
        error_page 404 /backend_404.html;

    location /backend_404.html {
        proxy_pass http://backend_example/example/${repo}/404.html;
        proxy_intercept_errors on;

        error_page 404 /error.html;

    location /error.html {
        ssi on;
        root /usr/share/nginx/html;

What’s working:

  • if the file 404.html is available on the backend it will be delivered as intended
  • if the 404.html is not available on the backend I get the standard 404 from nginx instead of the local custom error.html
  • if I replace error_page 404 /backend_404.html; with error_page 404 /error.html; the error.html location also works

What I want to achieve:

  • if 404.html exists on the backend, deliver it
  • if 404.html not exist, deliver a custom error page error.html instead of the default one