Implementing Multiple Website Environments on a Single Nginx Server: Serving Both Demo and Production Versions
Managing multiple versions of a websiteโsuch as a production environment and a demo instanceโon a single server can enhance development workflows and streamline deployment. If you’re using Nginx as a reverse proxy, configuring it to serve different sites from the same server is achievable but requires proper setup. This article explores how to set up Nginx to host both a production site at the root URL (/
) and a demo version at a sub-path (/demo/
), including troubleshooting common issues.
Understanding the Setup
Suppose your goal is:
- Serve the production website from the root path (
/
) - Serve the demo version from the
/demo/
path
Your directory structure might look like:
/usr/share/nginx/html/ # Production site files
/usr/share/nginx/demo/ # Demo site files
Configuration Snippet
A typical Nginx server block to achieve this might look like:
“`nginx
server {
listen 80;
# Serve demo site at /demo/
location /demo/ {
alias /usr/share/nginx/demo/; # Note the use of 'alias' instead of 'root'
index index.html;
try_files $uri /index.html;
}
# Serve production site at /
location / {
root /usr/share/nginx/html;
index index.html;
try_files $uri /index.html;
}
}
“`
Key Points and Troubleshooting
- Using
alias
vsroot
: - When serving sub-paths like
/demo/
,alias
is usually more appropriate because it directly maps the URL path to the directory. -
With
alias
, ensure the path ends with a/
if the directory structure warrants it. -
Handling URL Path Matching:
- With
try_files $uri /index.html;
, requests to nested routes (like/demo/about
) should resolve correctly. -
For single-page applications (SPA), this pattern helps fallback to index.html when a route isnโt found.
-
Ensuring Files Exist:
- Verify that the files for both sites are correctly placed in their respective directories.
-
Confirm permissions are appropriate so Nginx can read these files.
-
Docker Considerations:
- If you’re running