Smart Systems for Home

Plain how-to guides for smart home, security and home Wi-Fi

Serve Static Files from Multiple Nginx Locations

· 6 min read · Home Tech

In this article
  1. What You'll Need
  2. Step-by-Step
  3. Common Mistakes
  4. Tips
  5. Troubleshooting
  6. Frequently Asked Questions

This guide shows you how to configure Nginx to serve static files (like images, CSS, JavaScript, PDFs) from multiple distinct directories or URL paths. You'll learn to set up separate location blocks, each pointing to a different folder on your server, so you can organize content by type, project, or user uploads. You'll need a working Nginx installation and basic familiarity with editing its configuration files.

What You'll Need

  • A server with Nginx installed (any modern version, e.g., 1.18+).
  • Root or sudo access to edit Nginx configuration files.
  • At least two directories containing static files you want to serve.
  • Basic knowledge of the command line and text editors (like nano or vim).

Step-by-Step

  1. Locate your Nginx configuration file. The main configuration is usually at /etc/nginx/nginx.conf, but you'll often work with site-specific files in /etc/nginx/sites-available/ (or /etc/nginx/conf.d/). Check your setup with nginx -T to see the full active configuration.
  2. Open the server block you want to modify. For example, edit /etc/nginx/sites-available/example.com with sudo nano /etc/nginx/sites-available/example.com. If you're using the default config, that's /etc/nginx/sites-available/default.
  3. Create or identify the directories you'll serve. For this guide, we'll use two: /var/www/site/images and /var/www/site/documents. Ensure these directories exist and contain your files. You can create them with sudo mkdir -p /var/www/site/images /var/www/site/documents.
  4. Add a location block for the first directory. Inside your server { } block, add a location directive that maps a URL path to the directory. For example, to serve files from /var/www/site/images when someone visits example.com/images/photo.jpg, add:
    location /images/ {
        alias /var/www/site/images/;
        autoindex off;
    }
    
    The alias directive replaces the matched part of the URL with the specified path. The trailing slashes are important: /images/ matches the URL prefix, and /var/www/site/images/ must end with a slash to correctly append the rest of the request.
  5. Add a second location block for another directory. Similarly, to serve documents from /var/www/site/documents at example.com/files/, add:
    location /files/ {
        alias /var/www/site/documents/;
        autoindex off;
    }
    
    You can add as many such blocks as you need, each with a unique URL prefix.
  6. Set appropriate permissions. Ensure the Nginx user (usually www-data on Debian/Ubuntu, or nginx on RHEL) has read access to the directories and files. For example: sudo chown -R www-data:www-data /var/www/site or at least sudo chmod -R 755 /var/www/site.
  7. Test the configuration. Run sudo nginx -t to check for syntax errors. If it says the test is successful, proceed.
  8. Reload Nginx. Apply the changes with sudo systemctl reload nginx (or sudo service nginx reload on older systems). This reloads the config without dropping connections.
  9. Verify in a browser. Visit http://yourdomain.com/images/photo.jpg and http://yourdomain.com/files/report.pdf to confirm the files are served correctly.

Common Mistakes

  • Missing trailing slashes. Both the location prefix and the alias path must end with a slash. Without them, Nginx may not match correctly or may append paths incorrectly.
  • Using root instead of alias. root appends the full request URI to the specified path, which often leads to 404 errors when the directory structure doesn't match. Use alias when the URL path does not correspond directly to the filesystem path.
  • Forgetting to reload. Changes don't take effect until you reload or restart Nginx. Always run nginx -t first.
  • Overlapping location blocks. If you have a location like / that handles everything, it may catch requests before your specific locations. Nginx chooses the longest matching prefix, so more specific locations like /images/ will take precedence, but be aware of ordering if you use regex locations.
  • Permission errors. If files are not readable by the Nginx user, you'll get 403 Forbidden. Check directory permissions and ownership.

Tips

  • Use try_files for fallback. If you want to serve a default file (like index.html) when the requested file doesn't exist, you can add try_files $uri $uri/ /fallback.html; inside a location block.
  • Enable caching headers. For static assets, add expires 30d; or add_header Cache-Control "public"; to reduce server load and improve performance.
  • Use regex locations for patterns. If you need to serve files based on a pattern (e.g., all .jpg files), use location ~*\.(jpg|jpeg|png)$ { ... }. But be careful: regex locations are evaluated in order, so place them after prefix locations.
  • Consider a dedicated server block. If you're serving static files from multiple subdomains or ports, you might create separate server blocks instead of multiple locations.
  • Enable autoindex for directory listing. If you want to allow browsing of a directory, set autoindex on; inside the location block. This is useful for public file sharing.

Troubleshooting

  • 404 Not Found. Check the alias path: does it exist? Does it have a trailing slash? Use ls -la /var/www/site/images/ to confirm. Also, check that the file name matches exactly (case-sensitive on Linux).
  • 403 Forbidden. This usually means permission issues. Verify the Nginx user can read the directory and files: sudo -u www-data ls /var/www/site/images/. If not, adjust permissions or ownership.
  • 500 Internal Server Error. Often a configuration syntax error. Run sudo nginx -t and look for error messages. Common issues include missing semicolons or braces.
  • Files are being served from the wrong directory. Double-check your alias paths. If you used root by mistake, the URL path is appended to the root, so /images/photo.jpg would look for /var/www/site/images/photo.jpg if root is /var/www/site – that might work, but if your directory is elsewhere, it fails.
  • Changes not taking effect. After editing, run sudo nginx -t and then sudo systemctl reload nginx. If you're using a reverse proxy or CDN, clear its cache.
  • Check Nginx error logs. Look at /var/log/nginx/error.log for detailed messages. This often points directly to the issue, like a missing file or permission problem.

Frequently Asked Questions

Can I serve files from outside the web root?

Yes, using alias you can point to any directory on the filesystem, as long as Nginx has read permissions. This is common for user uploads stored outside the main site directory.

What's the difference between root and alias?

root sets the base directory, and the full request URI is appended to it. alias replaces the matched location prefix with the specified path. Use alias when the URL path doesn't map directly to the filesystem path.

How do I serve files with a different extension, like .html or .pdf?

Nginx serves any file type by default, as long as it exists and permissions allow. You don't need to specify extensions. If you want to set correct MIME types, ensure the include mime.types; directive is in your http block (it usually is).

Can I use regular expressions to match multiple locations?

Yes, you can use regex locations like location ~* \.(png|jpg)$ { ... } to handle all image files. However, regex locations are checked in order, so place them after any prefix locations you want to take precedence.

How do I enable directory listing?

Set autoindex on; inside the location block. This will show a list of files when a directory is requested without an index file.

What if I want to serve files from a different drive or mount?

Just point the alias to the absolute path of that mount point, e.g., alias /mnt/data/uploads/;. Ensure the mount is accessible and permissions are set.