How to Configure Alias in Nginx: Syntax and Examples
To configure an
alias in Nginx, use the alias directive inside a location block to map a URL path to a specific directory on your server. This tells Nginx to serve files from the given directory when the URL matches the location.Syntax
The alias directive is used inside a location block to specify the directory that should be served for matching requests. Unlike root, alias replaces the entire location path with the given directory path.
- location /url/path/: The URL path to match.
- alias /file/system/path/: The directory on the server to serve files from.
Make sure the alias path ends with a slash if the location ends with a slash.
nginx
location /images/ {
alias /var/www/static/images/;
}Example
This example shows how to serve files requested at /images/ from the directory /var/www/static/images/. When a user requests /images/pic.jpg, Nginx will serve the file /var/www/static/images/pic.jpg.
nginx
server {
listen 80;
server_name example.com;
location /images/ {
alias /var/www/static/images/;
autoindex on;
}
}Output
When accessing http://example.com/images/pic.jpg, Nginx serves /var/www/static/images/pic.jpg file.
Common Pitfalls
One common mistake is mixing alias with root syntax or forgetting the trailing slash on the alias path, which causes incorrect file paths and 404 errors.
Also, alias must be used carefully with regex locations because it replaces the entire location path.
nginx
location /static/ { root /var/www/html; # Wrong if you want to map /static/ to /var/www/html/static/ } location /static/ { alias /var/www/html/static/; # Correct usage }
Quick Reference
| Directive | Purpose | Notes |
|---|---|---|
| alias | Maps a URL location to a specific directory | Path must end with slash if location ends with slash |
| root | Sets root directory for requests | Appends URI after location to root path |
| location | Defines URL path to match | Used with alias or root to serve files |
Key Takeaways
Use
alias inside a location block to map a URL path to a specific directory.Ensure the
alias path ends with a slash if the location path ends with a slash.Do not confuse
alias with root; they handle paths differently.Common errors include missing trailing slashes and mixing
alias with root syntax.Test your configuration with real requests to verify correct file serving.