I have a configuration where I want to return a custom error from within a named location. However, instead I receive the standard nginx error page. I can get the custom error from a non-named location though.
To reproduce the issue, I created this simple docker-based setup:
Dockerfile:
FROM nginx:1.17.9
COPY default.conf /etc/nginx/conf.d/default.conf
COPY 404.html /usr/share/nginx/html/404.html
default.conf:
server {
listen 80;
server_name localhost;
#recursive_error_pages on;
location = /404.html {
root /usr/share/nginx/html;
internal;
}
# redirect server error pages to the static page /50x.html
#
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root /usr/share/nginx/html;
}
location / {
# used in a more complex setup, this is just a minimal config
# # See http://stackoverflow.com/a/20694873
error_page 404 = @fwd;
return 404;
}
location @fwd {
root /usr/share/nginx;
error_page 404 /404.html;
}
}
The 50x errors are not interesting here, I've adapted the config from the nginx docker image.
Uing something other than 404 to redirect to the named location does not make a difference.
404.html:
<!DOCTYPE html>
<html>
<head><title>404</title></head>
<body>
my 404
</body>
</html>
Build: docker build -t mynginx . and start docker run --rm -p 8080:80 --name mynginx mynginx.
Now pointing the browser to http://localhost:8080/index.html should return the standard welcome page, while http://localhost:8080/inexistent.html will return a internal nginx 404 page, not the custom one I configured.
Is there a way to actually make this work from within the named location?
try_files /404.html =404;