To set up an Nginx reverse proxy for multiple sites using path variables, you can use the Nginx location
block to route incoming requests based on the requested paths. Each location
block will be responsible for proxying requests to the corresponding backend server based on the path.
Assuming you have two backend servers running on different ports (e.g., http://backend1:3000
and http://backend2:4000
), here's how you can configure Nginx to act as a reverse proxy for them using path variables:
Install Nginx (if you haven't already) and create the configuration file. For example,
/etc/nginx/sites-available/multisite-reverse-proxy
.Configure the Nginx virtual host to use the
location
block for each site:
nginxserver { listen 80; server_name example.com; # Your domain name location /site1/ { proxy_pass http://backend1:3000/; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; } location /site2/ { proxy_pass http://backend2:4000/; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; } # Add more location blocks for additional sites if needed location / { # Default location block, can handle other requests if not matched above # You can return an error or serve a static file here if needed return 404; } }
In this configuration:
- Requests to
http://example.com/site1/*
will be forwarded tohttp://backend1:3000/*
. - Requests to
http://example.com/site2/*
will be forwarded tohttp://backend2:4000/*
. - Any other requests will return a 404 error (you can customize this behavior as needed).
- Create a symbolic link to enable the configuration:
bashsudo ln -s /etc/nginx/sites-available/multisite-reverse-proxy /etc/nginx/sites-enabled/
- Test the Nginx configuration for syntax errors:
bashsudo nginx -t
- If there are no errors, reload Nginx to apply the changes:
bashsudo service nginx reload
With this setup, Nginx will act as a reverse proxy for multiple backend sites based on the path. Remember to adjust the configuration according to your actual backend server URLs and other requirements.