How to Serve Static Files with Nginx: Simple Guide
To serve static files with
nginx, use the location block with the root or alias directive pointing to your static files folder. Nginx will then deliver files like HTML, CSS, and images directly to clients without extra processing.Syntax
The basic syntax to serve static files in nginx uses a location block inside a server block. You specify the URL path to match and use root or alias to set the folder where files are stored.
- location: Defines the URL path to serve files from.
- root: Sets the base directory for static files. The full file path is
root + URI. - alias: Sets the exact directory to serve files from, replacing the matched location path.
nginx
server {
listen 80;
server_name example.com;
location /static/ {
root /var/www/html;
}
}Example
This example shows how to serve static files from the /var/www/html/static folder when users visit http://example.com/static/. Nginx will deliver files like style.css or image.png directly.
nginx
server {
listen 80;
server_name example.com;
location /static/ {
root /var/www/html;
# A request to /static/style.css serves /var/www/html/static/style.css
}
}Output
When visiting http://example.com/static/style.css, nginx serves the file /var/www/html/static/style.css if it exists.
Common Pitfalls
Common mistakes when serving static files with nginx include:
- Using
rootwith a trailing slash incorrectly, causing wrong file paths. - Confusing
rootandaliasdirectives, which behave differently. - Not setting correct file permissions, so nginx cannot read files.
- Forgetting to reload or restart nginx after configuration changes.
Example of wrong vs right usage:
nginx
# Wrong usage with alias (causes 404): location /static/ { alias /var/www/html/static/; } # Right usage with alias (note trailing slash on alias): location /static/ { alias /var/www/html/static/; }
Quick Reference
| Directive | Purpose | Notes |
|---|---|---|
| location | Defines URL path to match | Use to specify where static files are served |
| root | Sets base directory for files | Full path = root + URI after location |
| alias | Sets exact directory for files | Replaces location path, be careful with trailing slashes |
| listen | Sets port nginx listens on | Usually 80 for HTTP |
| server_name | Defines domain name | Matches requests for this domain |
Key Takeaways
Use the location block with root or alias to serve static files in nginx.
root appends the URI to the directory path; alias replaces the location path.
Ensure file permissions allow nginx to read static files.
Reload nginx after changing configuration to apply updates.
Avoid trailing slash mistakes with alias to prevent 404 errors.