Nginx: Disallow index.html in URL

Posted by Martin Vilcans on Server Fault See other posts from Server Fault or by Martin Vilcans
Published on 2013-10-23T09:52:19Z Indexed on 2013/10/23 9:59 UTC
Read the original article Hit count: 240

Filed under:
|

We're generating a site consisting of only static files (using Assemble).

Having the .html extension on URLs looks so nineties, so we generate every static HTML file in its own directory and call it index.html. For example, the url http://www.example.com/foo/bar/ is in the file /var/www/foo/bar/index.html.

This works well, but there is one small thing nagging me: Now there are two possible URLs to the same resource:

  1. http://www.example.com/foo/bar/ (slash URL)
  2. http://www.example.com/foo/bar/index.html (index.html URL)

By accident someone may link to the index.html form of the URL, which is bad for SEO and looks ugly (remember the nineties?).

Is it possible in Nginx to give a 404 error on the index.html URL, but serve the slash URL?

I tried this:

location ~ /index\.html$ {
    return 404;
}

But it seems that Nginx does some internal rewrite of the slash URL to the index.html URL, and then matches this location so we get a 404 even on the slash URL.

Note that to catch mistakes, we want index.html URLs to be an error, not just redirect to the slash URL.

© Server Fault or respective owner

Related posts about nginx

Related posts about static-files