Remove index.html from URL

May 3, 2015 5.6k views
LEMP Nginx

Hello,

I'm setting up a new site with nginx and stumbled upon a problem with the url on the frontpage. When I go into my site (for example) http://domain.com then it opens http://domain.com/index.

I would like to remove index and only have it at http://domain.com.

I have successfully removed .html extension on pages (domain.com/aboutus.html -> domain.com/aboutus) but can't figure out how I can go from (domain.com/index -> domain.com)

This is how my server is configured:

server {
listen 80 defaultserver;
listen [::]:80 default
server ipv6only=on;
root /usr/share/nginx/html;

# Make site accessible from http://localhost/
  server_name domain.com;

rewrite ^(/.+)\.html$ $scheme://$host$1 permanent;

location / {
    index  index.html;
    try_files $uri.html $uri $uri/ @handler;
    autoindex on;
}
3 Answers

@gabriel1140595

The autoindex on; definition is more so meant to allow for directory listings in the event an index file is not found. This means that in the event index.html is not found, the entire directory contents will be exposed to the visitor. In most cases, this is viewed as a security risk and should only be on when other directories are locked down to prevent traversing, except to those you specifically allow.

The index definition should ideally be moved to nginx.conf under http { }.

As an example, here's a quick reference for http { } and a server { } block:

http
{
    index        index.php index.html;

    #+ Additional Configuration ....
    #+ ....
    #+ ....
    #+ .... etc
}


server
{
    listen       [port];
    server_name  [domain.ext] [www.domain.ext];

    root         [/path/to/content/dir];

    error_log    [/path/to/error.log];
    access_log   [/path/to/access.log];

    location / {
        try_files  $uri  $uri/  index.php;
        #+ or, for HTML instead of PHP
        #+ try_files  $uri  $uri/  index.html;
    }
}
  • Hello!

    I almost got that setup (except from my new location) which is:
    location / {
    try_files $uri.html $uri $uri/ @handler;
    }

    If I use:
    location / {
    try_files $uri $uri/ index.html;
    }

    I'll get a 404. Can't seem to get rid of the domain.com/index

    If i do a 301 redirect like this:

    location /index {
    return 301 https://domain.com/;
    }

    my browser says that it can't reach it because of to many redirects

Any solution to this? Seems like a very common issue that Google cannot solve. My God! There are dozens of instructions out there online, all are wrong. WtF?

Please DO, remove index.html and index.php from all URLs, redirect to the non-index.html and non-index.php pages. And without using an if statement.

Have another answer? Share your knowledge.