Nginx location block to serve one file under many names
Every static site ends up with a pile of one-off files at the root: /robots.txt, /favicon.ico, /humans.txt, /.well-known/security.txt, and so on. I used to have a location block per file. Nowadays I use one regex block and a map, which keeps the config short and makes it obvious where each file lives on disk.
map $uri $one_file {
/robots.txt /srv/meta/robots.txt;
/humans.txt /srv/meta/humans.txt;
/favicon.ico /srv/meta/favicon.ico;
/.well-known/security.txt /srv/meta/security.txt;
}
server {
listen 443 ssl;
server_name example.com;
location ~ ^/(robots\.txt|humans\.txt|favicon\.ico|\.well-known/security\.txt)$ {
alias $one_file;
add_header Cache-Control "public, max-age=86400";
access_log off;
log_not_found off;
}
# ... main site below
}
alias points at a file on disk, not a directory, which is exactly what I want here. access_log off keeps bot noise out of the logs. log_not_found off means a missing file returns 404 silently instead of littering error.log.
See also /posts/caddy-vs-nginx-switch/.