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

前端 未结 7 595
[愿得一人]
[愿得一人] 2020-12-30 10:17

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:

<
相关标签:
7条回答
  • 2020-12-30 10:37

    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;
    }
    
    0 讨论(0)
  • 2020-12-30 10:39

    For the root /index.html, the answer from Nicolas resulted in a redirect loop, so I had to search for other answers.

    This question was asked on the nginx forums and the answer there worked better. http://forum.nginx.org/read.php?2,217899,217915

    Use either

    location = / {
      try_files /index.html =404;
    }
    
    location = /index.html {
      internal;
      error_page 404 =301 $scheme://domain.com/;
    }
    

    or

    location = / {
      index index.html;
    }
    
    location = /index.html {
      internal;
      error_page 404 =301 $scheme://domain.com/;
    }
    
    0 讨论(0)
  • 2020-12-30 10:43

    The solutions quoting $scheme://domain.com/ assume that the domain is hard-coded. It was not in my case and so I used:

    location / {
        ...
    
        rewrite index.html $scheme://$http_host/ redirect;
    
        ... }
    
    0 讨论(0)
  • 2020-12-30 10:45

    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://foo.com/bar/index.html, but it breaks http://foo.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.

    0 讨论(0)
  • 2020-12-30 10:51

    This one works:

    # redirect dumb search engines
    location /index.html {
        if ($request_uri = /index.html) {
            rewrite ^ $scheme://$host? permanent;
        }
    }
    
    0 讨论(0)
  • 2020-12-30 11:01

    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;
    }
    
    0 讨论(0)
提交回复
热议问题