Linux

How to enable directory listing in Nginx

To enable directory listing in Nginx, you need to configure the Nginx server block (also known as a virtual host) to allow directory browsing. Follow these steps:

1. Access Your Nginx Configuration

- Open the Nginx configuration file for your website. Typically, this will be in one of the following locations:
  - For a specific site configuration: /etc/nginx/sites-available/your-site-name
  - For the main Nginx configuration: /etc/nginx/nginx.conf

2. Modify the Configuration to Enable Directory Listing

- Add or modify the configuration block for the location where you want directory listing to be enabled. You need to use the autoindex on; directive.

Here is an example configuration block:

server {
    listen 80;
    server_name example.com;
    root /var/www/html;

    location / {
        autoindex on;
        # Optional: Add fancy indexing and charset if needed
        autoindex_exact_size off;   # Displays file sizes in human-readable format
        autoindex_localtime on;     # Displays file modification times in local timezone
        charset utf-8;              # Ensure proper encoding
    }

    location /downloads/ {
        autoindex on;   # Enable directory listing for /downloads/ directory
    }
}

- The autoindex on; enables directory listing in the root or in a specific location (like /downloads/ in the example).

3. Save the Configuration and Test Nginx

- Save the configuration file after making the changes.
- Test the configuration for any syntax errors using:

sudo nginx -t

If there are no errors, the output will show something like:

nginx: configuration file /etc/nginx/nginx.conf test is successful

4. Reload Nginx

- After confirming the syntax is correct, reload Nginx to apply the changes:

sudo systemctl reload nginx

5. Verify Directory Listing

- Now, when you access the directory via a browser (e.g., http://example.com/ or http://example.com/downloads/), you should see a directory listing.

Notes:
- Security Consideration: Be cautious when enabling directory listing. Ensure that sensitive directories are properly restricted using access controls, and that only the necessary directories are exposed.