Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

nginx : rewrite rule to remove /index.html from the $request_uri

Tags:

nginx

pcre

I've seen a few ways to rewrite the $request_uri and add the index.html to it when that particular file exists in the file system, like so:

if (-f $request_filename/index.html) {
    rewrite (.*) $1/index.html break;
}

but i was wondering if the opposite is achievable:

i.e. when somebody requests http://example.com/index.html, they're redirected to http://example.com

Because the nginx regexp is perl compatible, i tried something like this:

if ( $request_uri ~* "index\.html$" ) {
    set $new_uri $request_uri ~* s/index\.html//
    rewrite $1 permanent;
}

but it was mostly a guesswork, is there any good documentation describing the modrewrite for nginx ?

like image 734
tjmc Avatar asked Apr 15 '11 11:04

tjmc


2 Answers

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;
}
like image 189
Jackson Avatar answered Sep 25 '22 11:09

Jackson


For some reason most of the solutions mentioned here did not work. The ones that worked gave me errors with missing / in the url. This solution works for me.

Paste in your location directive.

if ( $request_uri ~ "/index.html" ) {
  rewrite ^/(.*)/ /$1 permanent;
}
like image 23
Hendrik Avatar answered Sep 24 '22 11:09

Hendrik