Nginx: Disallow index.html in URL
- by Martin Vilcans
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:
http://www.example.com/foo/bar/ (slash URL)
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.