Enable directory listing in nginx

nginx logoEnabling directory listing in a folder in nginx seems simple enough with just an autoindex on; directive inside the location directive. However, for some reason, it didn’t work for me.

I finally got it to work by moving the root directive out of location.
So, if you have something like this :

server {
        listen   80;
        server_name  domain.com www.domain.com;
        access_log  /var/...........................;
        location / {
                root   /path/to/root;
                index  index.php index.html index.htm;
        }
        location /somedir {
               autoindex on;
        }
}

Change it to :

server {
        listen   80;
        server_name  domain.com www.domain.com;
        access_log  /var/...........................;
        root   /path/to/root;
        location / {
                index  index.php index.html index.htm;
        }
        location /somedir {
               autoindex on;
        }
}

Directory indices should show flawlessly now.
(A live example can be found here.)

5 Comments

  1. melf says:

    Nice info, thanks

  2. Peldi Guilizzoni says:

    Thank you for this, it helped me today.

  3. zyingfei says:

    thx. it looks like a bug?

    1. Ellimist says:

      Not a bug, actually. Putting a root inside a location block is perfectly valid if all the location blocks have root defined.

      This is perfectly valid :

      server {
              server_name  domain.com;
              access_log  /var/...........................;
              location / {
                      root   /path/to/root;
                      index  index.php index.html index.htm;
              }
              location /somedir {
                     root   /path/to/root/somedir;
                     autoindex on;
              }
      }

      This is not :

      server {
              server_name  domain.com;
              access_log  /var/...........................;
              location / {
                      root   /path/to/root;
                      index  index.php index.html index.htm;
              }
              location /somedir {
                     autoindex on;
              }
      }

      See : http://wiki.nginx.org/Pitfalls#Root_inside_Location_Block

  4. Babak says:

    Thank you very much. You saved me a lot of time.