Nginx – “Hide” .html file extensions using nginx rewrites

nginxrewrite

I'm serving up a static site via nginx, and my goal is to replace URL's that look like:

http://foo.com/bar.html

with

http://foo.com/bar

The key being no trailing slash. I am currently doing something similar using location aliases but this is tedious because it requires a location block for every file, and it also appends a trailing slash since nginx looks at aliases as directories:

    location / {
        root    /srv/www/foo/public_html;
        index   index.html;
    }

    location /bar1 {
        alias /srv/www/foo/public_html/;
        index bar1.html;
    }

    location /bar2 {
        alias /srv/www/foo/public_html/;
        index bar2.html;
    }

And so on. I've read through the documentation on rewrites, and I can't seem to synthesize what's being said in to what I need it to do. I'm not coming in from an Apache background; nginx is my first foray in to web servers so I'm sure I'm missing something obvious since my HTTP background is weak. Thanks in advance for any help you can provide.

Best Answer

try_files should be what you want.

Something like this:

try_files $uri.html $uri $uri/ =404;