I'd like to host HTML files uploaded by users and I need to display custom 404 if they provided it, or display my own 404 otherwise.
Sample workflow:
pages/page1.html does not exists but $user has uploaded 404.html so display it404.html so display simple message myselfSo far I have covered the steps 1 & 2 but cannot make the logic for last one.
My /simplified/ config:
# each user has their own storage path etc
# just to illustrate
map $host $user {
dog.example.com group/1/2/3;
cat.example.com group/4/5/1;
dog-want-cookie.example.com group/9/9/9;
}
server {
listen 8000;
server_name ~^(?<vhost>[^.]*)\.example\.com$;
root /sites/$user;
location / {
try_files $uri $uri/index.html @not_found;
}
location @not_found {
internal;
error_page 404 /404.html;
}
}
Not sure where to "invoke" a config for my own error "page".
location @my404 {
return 404 "Page not found.";
}
I'm using Nginx 1.19.3 on Debian.
Use error_page to invoke the named location rather than try_files. See this document for details.
For example:
error_page 404 @not_found;
location / {
try_files $uri $uri/index.html =404;
}
Use try_files to test the existence of the 404.html file.
For example:
location @not_found {
try_files /404.html /fallback404.html =404;
}
You do not need to mark named locations as internal, as they cannot be accessed externally.
In the above example, the fallback404.html file is in the same document root. The =404 is necessary for the syntax, but is never reached as the second file always exists. See this document for details.
To use a fallback 404.html file in a different document root, you can cascade two named locations.
For example:
location @not_found {
try_files /404.html @fallback;
}
location @fallback {
root /path/to/fallback/files;
try_files /404.html =404;
}
Alternatively, you can replace the content of the @fallback location with your return statement.
For example:
location @fallback {
return 404 "Page not found.";
}