Home > OS >  How to show a custom 404 from the document root rather than a subdirectory using nginx?
How to show a custom 404 from the document root rather than a subdirectory using nginx?

Time:05-05

I have the following nginx.conf section:

# valid url
location /foo/bar/ {
    proxy_pass http://my_server/foo/bar/;
}


# redirect base url to index.html
location = / {
    root   /usr/share/nginx/html;
    index  index.html;
}


# anything not listed above to 404
location / {
    return 404;
}

error_page 404 404.html;
error_page 500 502 503 504 50x.html;

When I launch my nginx server and request a route like: https://my_server/blah/, i am correctly redirected to https://my_server/404.html page where I can see my custom 404. However, if I make a another request to a url with a subdirectory: https://my_server/blah/baz, my nginx server tries to find https://my_server/blah/404.html

my_server-reverse_proxy-1 | 2022/05/02 23:05:35 [error] 7#7: *1 open() "/usr/share/nginx/html/blah/404.html" failed (2: No such file or directory), client: 11.11.111.111, server: my_server.com, request: "GET /blah/404.html HTTP/1.1", host: "my_server.com"

How do I properly configure my NGINX server to handle 404s for non existent sub directory urls?

CodePudding user response:

To load the error documents from the document root, the relative URL for them should start with a /

error_page 404 /404.html;
error_page 500 502 503 504 /50x.html;

The nginx documentation for error_page shows this code with the leading slash. Including it is the usual practice.

  • Related