nginx try_files index conflict

Gabriel asked:

I’m trying to achieve a setup with nginx to:

  • use index.html for ‘/’
  • clean up .html urls
  • default to 404 if no corresponding file is found

My server block looks like this:

server {
    listen      80;

    index index.htm;

    location / {
        root "static";
        try_files $uri.html =404;

Right now, visiting ‘/’ goes to 404. I’ve tried common solutions like:

try_files $uri.html $uri/ =404;

but these allow both ‘/page’ and ‘/page.html’ as valid urls and I want to avoid duplicates.

Any suggestions?


My answer:

Your root directive has two problems:

  1. It uses a relative path. When a relative path is used, it’s relative to a default directory compiled into nginx. Do you know which one that is? It’s best to specify absolute paths.
  2. It is in the wrong place. The root directive should be specified in the server block. This is one of the most common nginx misconfigurations.

View the full question and answer on Server Fault.

Creative Commons License
This work is licensed under a Creative Commons Attribution-ShareAlike 3.0 Unported License.