Serve Static Files from Multiple Nginx Locations
In this article
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
- 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 withnginx -Tto see the full active configuration. - Open the server block you want to modify. For example, edit
/etc/nginx/sites-available/example.comwithsudo nano /etc/nginx/sites-available/example.com. If you're using the default config, that's/etc/nginx/sites-available/default. - Create or identify the directories you'll serve. For this guide, we'll use two:
/var/www/site/imagesand/var/www/site/documents. Ensure these directories exist and contain your files. You can create them withsudo mkdir -p /var/www/site/images /var/www/site/documents. - Add a location block for the first directory. Inside your
server { }block, add alocationdirective that maps a URL path to the directory. For example, to serve files from/var/www/site/imageswhen someone visitsexample.com/images/photo.jpg, add:location /images/ { alias /var/www/site/images/; autoindex off; }Thealiasdirective 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. - Add a second location block for another directory. Similarly, to serve documents from
/var/www/site/documentsatexample.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. - Set appropriate permissions. Ensure the Nginx user (usually
www-dataon Debian/Ubuntu, ornginxon RHEL) has read access to the directories and files. For example:sudo chown -R www-data:www-data /var/www/siteor at leastsudo chmod -R 755 /var/www/site. - Test the configuration. Run
sudo nginx -tto check for syntax errors. If it says the test is successful, proceed. - Reload Nginx. Apply the changes with
sudo systemctl reload nginx(orsudo service nginx reloadon older systems). This reloads the config without dropping connections. - Verify in a browser. Visit
http://yourdomain.com/images/photo.jpgandhttp://yourdomain.com/files/report.pdfto 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
rootinstead ofalias.rootappends the full request URI to the specified path, which often leads to 404 errors when the directory structure doesn't match. Usealiaswhen 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 -tfirst. - 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_filesfor fallback. If you want to serve a default file (likeindex.html) when the requested file doesn't exist, you can addtry_files $uri $uri/ /fallback.html;inside a location block. - Enable caching headers. For static assets, add
expires 30d;oradd_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 -tand look for error messages. Common issues include missing semicolons or braces. - Files are being served from the wrong directory. Double-check your
aliaspaths. If you usedrootby mistake, the URL path is appended to the root, so/images/photo.jpgwould look for/var/www/site/images/photo.jpgif 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 -tand thensudo 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.logfor 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.