When working with Nginx server blocks, a common requirement is to serve different content from separate filesystem locations based on URL paths. The typical scenario involves:
- Main site content from
/primary/path
- Specific subdirectories from alternative roots (e.g.,
/alternate/path
)
Your existing setup attempts to use both root
and rewrite
directives, which creates a processing loop:
location /petproject {
root /home/me/pet-Project/website;
index index.html;
rewrite ^/petproject(.*)$ /$1;
}
The proper approach is to use alias
instead of root
for path-specific mappings:
server {
listen 80;
server_name www.domain.com;
location / {
root /home/me/Documents/site1;
index index.html;
}
location /petproject {
alias /home/me/pet-Project/website/;
index index.html;
}
# Error handling remains unchanged
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root /usr/share/nginx/html;
}
}
Directive | Behavior | When to Use |
---|---|---|
root | Appends URI to path | For standard document roots |
alias | Replaces matched path | For alternate content locations |
For more complex scenarios with multiple subdirectories:
location /special {
alias /custom/storage/;
try_files $uri $uri/ /special-fallback.html;
location ~* \.(php|php5)$ {
fastcgi_pass unix:/var/run/php-fpm.sock;
include fastcgi_params;
}
}
- Always include trailing slashes in alias paths
- Check filesystem permissions (nginx worker process needs read access)
- Verify path mappings with
nginx -T
(test configuration) - Monitor error logs (
/var/log/nginx/error.log
) for path resolution issues
When setting up Nginx to serve different website sections from different filesystem locations, developers often encounter path resolution issues. The key is understanding how Nginx processes root
versus alias
directives.
The configuration attempts to serve /petproject
from a different directory, but the rewrite
causes Nginx to reprocess the request through location matching:
location /petproject {
root /home/me/pet-Project/website;
index index.html;
rewrite ^/petproject(.*)$ /$1; # This causes reprocessing
}
Option 1: Using alias Directive
The most straightforward solution replaces root
with alias
and removes the rewrite:
location /petproject {
alias /home/me/pet-Project/website/;
index index.html;
try_files $uri $uri/ /index.html;
}
Option 2: Proper root Configuration
If you prefer using root
, modify the path structure:
location /petproject/ {
root /home/me/pet-Project/website;
index index.html;
try_files $uri $uri/ /petproject/index.html;
}
Directive | Behavior | When to Use |
---|---|---|
root |
Appends full URI path to root | When maintaining URI structure |
alias |
Replaces location path with alias path | When changing path structure |
- Missing trailing slashes in directory paths
- Not considering
try_files
for single-page apps - Permission issues on the new root directory
Always verify changes with:
sudo nginx -t
sudo systemctl reload nginx