nginx location index directive not working

2019-07-03 18:58发布

问题:

I'm new to nginx and I just can't determine why my nginx config doesn't work as expected. All I want to do is to make nginx prioritize index.html over index.php for every web root (/) request.

This is my nginx config:

user www-data;
worker_processes 4;
pid /var/run/nginx.pid;

events {
    worker_connections 768;
    multi_accept on;
}

http {
    ##
    # Basic Settings
    ##

    server {
        location / {
            index   index.html index.php;
        }

        location ~ \.php$ {
            fastcgi_pass  localhost:9000;
            fastcgi_param SCRIPT_FILENAME
                          $document_root$fastcgi_script_name;
            include       fastcgi_params;
        }
    }

    sendfile on;
    tcp_nopush on;
    tcp_nodelay off;
    keepalive_timeout 15;
    keepalive_requests 100000;
    types_hash_max_size 2048;
    client_body_in_file_only clean;
    client_body_buffer_size 32K;

    client_max_body_size 300M;
    server_tokens off;

    # server_names_hash_bucket_size 64;
    # server_name_in_redirect off;

    include /etc/nginx/mime.types;
    default_type application/octet-stream;

    ----------------- cut ---------------

    ##
    # Virtual Host Configs
    ##

    include /etc/nginx/conf.d/*.conf;
    include /etc/nginx/sites-enabled/*;
}

Where's my error? What's the correct way to write this nginx config?

回答1:

Convention:

You should keep location and server declarations in virtual host files (/etc/nginx/conf.d/*.conf; and /etc/nginx/sites-enabled/*;, as you can see from the nginx conf). Files in /etc/nginx/conf.d/*.conf; are typically symlinked to files in /etc/nginx/sites-enabled/*; in order to become "enabled"

Some things to try

See my blog post here which has a setup similar to yours.

Try moving your index index.html index.html index.php files directive outside of a location {} block



回答2:

If you explicitly request /index.html, is it served? If not, you might want to add an explicit root /path/to/root; to your server {} block. Also verify that index.html has the correct permissions.

This will help with troubleshooting: It will force a 404 if the root index.html is not found. If that happens, at least you can check the logs to see were it was looking:

location = / {
  index   index.html;
}

Also, be sure to do nginx -s reload when changing the config.



标签: nginx