How to set index.html as root file in Nginx?

后端 未结 5 581
挽巷
挽巷 2020-12-08 09:14

How to set index.html for the domain name e.g. https://www.example.com/ - leads user to index.html in root directory.

I\'ve tried different things like:

         


        
5条回答
  •  情话喂你
    2020-12-08 09:55

    location / { is the most general location (with location {). It will match anything, AFAIU. I doubt that it would be useful to have location / { index index.html; } because of a lot of duplicate content for every subdirectory of your site.

    The approach with

    try_files $uri $uri/index.html index.html;

    is bad, as mentioned in a comment above, because it returns index.html for pages which should not exist on your site (any possible $uri will end up in that). Also, as mentioned in an answer above, there is an internal redirect in the last argument of try_files.

    Your approach

    location = / {
       index index.html;
    

    is also bad, since index makes an internal redirect too. In case you want that, you should be able to handle that in a specific location. Create e.g.

    location = /index.html {
    

    as was proposed here. But then you will have a working link http://example.org/index.html, which may be not desired. Another variant, which I use, is:

    root /www/my-root;
    
    # http://example.org
    # = means exact location
    location = / {
        try_files /index.html =404;
    }
    
    # disable http://example.org/index as a duplicate content
    location = /index      { return 404; }
    
    # This is a general location. 
    # (e.g. http://example.org/contacts <- contacts.html)
    location / {
        # use fastcgi or whatever you need here
        # return 404 if doesn't exist
        try_files $uri.html =404;
    }
    

    P.S. It's extremely easy to debug nginx (if your binary allows that). Just add into the server { block:

    error_log /var/log/nginx/debug.log debug;
    

    and see there all internal redirects etc.

提交回复
热议问题