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.

2 Answers 2

18

try_files should be what you want.

Something like this:

try_files $uri.html $uri $uri/ =404;
2
  • 1
    This worked, with the minor exception that $uri.html was causing a 500. I had to use "${uri}.html". Jan 5, 2012 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 foobar.com/bar and foobar.com/bar.html pointing to the same resource. Mar 5, 2012 at 9: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.

1
  • 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 Sep 17, 2019 at 23:49

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .