Need help figuring out how to put a “demo” and production versions on the same nginx

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

  1. Using alias vs root:
  2. When serving sub-paths like /demo/, alias is usually more appropriate because it directly maps the URL path to the directory.
  3. With alias, ensure the path ends with a / if the directory structure warrants it.

  4. Handling URL Path Matching:

  5. With try_files $uri /index.html;, requests to nested routes (like /demo/about) should resolve correctly.
  6. For single-page applications (SPA), this pattern helps fallback to index.html when a route isnโ€™t found.

  7. Ensuring Files Exist:

  8. Verify that the files for both sites are correctly placed in their respective directories.
  9. Confirm permissions are appropriate so Nginx can read these files.

  10. Docker Considerations:

  11. If you’re running

Leave a Reply

Your email address will not be published. Required fields are marked *