17

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.

Doug Stephen
  • 305
  • 1
  • 3
  • 8

2 Answers2

18

try_files should be what you want.

Something like this:

try_files $uri.html $uri $uri/ =404;
Shane Madden
  • 114,520
  • 13
  • 181
  • 251
  • 1
    This worked, with the minor exception that $uri.html was causing a 500. I had to use "${uri}.html". – Doug Stephen Jan 05 '12 at 17:54
  • 5
    Changing it to `try_files $uri.html $uri/ =404;` would be better SEO wise, as you wouldn't have two urls *http://foobar.com/bar* and *http://foobar.com/bar.html* pointing to the same resource. – Khaja Minhajuddin Mar 05 '12 at 09:35
7

Per the comment from @Khaja, the best answer is:

try_files $uri.html $uri/ =404;

So that only one copy of the resource is served (that with no .html extension). You don't want to divide your link strength over multiple URLs serving duplicate content. Find the documentation here.

Michael Hampton
  • 244,070
  • 43
  • 506
  • 972
Bryce
  • 561
  • 5
  • 13
  • I tried this. try_files $uri.html $uri/ =404; it broke loading of homepage without nominating myurl/index also broke loading of .css, .js etc – CodingMatters Sep 17 '19 at 23:49