nginx : rewrite rule to remove /index.html from the $request_uri
The following config allowed me to redirect /index.html
to /
and /subdir/index.html
to /subdir/
:
# Strip "index.html" (for canonicalization)
if ( $request_uri ~ "/index.html" ) {
rewrite ^(.*)/ $1/ permanent;
}
I use the following rewrite in the top level server clause:
rewrite ^(.*)/index\.html$ $1 permanent;
Using this alone works for most URLs, like http://example.com/bar/index.html
, but it breaks http://example.com/index.html
. To resolve this, I have the following additional rule:
location = /index.html {
rewrite ^ / permanent;
try_files /index.html =404;
}
The =404
part returns a 404 error when the file is not found.
I have no idea why the first rewrite alone isn't sufficient.