I'm trying to run multiple nodejs applications (using the express framework) all served on the same external port (80) but each under a subdirectory.
E.g. I want…
NodeJsApplication1 to be available at http://www.mydomain.com/NodeJsApplication1
NodeJsApplication2 to be available at http://www.mydomain.com/NodeJsApplication2
etc.
I have tried using Nginx as a proxy with a conf similar to the following.
server {
listen 80;
server_name www.mydomain.com;
location / {
root /var/www/html;
index index.html index.htm;
}
location /NodeJsApplication1/ {
proxy_pass http://0.0.0.0: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;
rewrite /NodeJsApplication1/(.*) /$1 break;
}
location /NodeJsApplication2/ {
proxy_pass http://0.0.0.0:3001;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
rewrite /NodeJsApplication2/(.*) /$1 break;
}
}
This works find for accessing the page but it breaks all relative URLs on the returning page. All scripts and css etc are pointing at the root (E.g. www.mydomain.com/styles/main.css).
I know I can use multiple subdomains but don't want to go down that route. I'd prefer to have subfolder proxy so it is all handled in software and I don't need to set up any DNS records for each application.
Is this even possible?
Update
Within the applications themselves all links are using relative paths. For example:
<link href="styles/main.css" />
<script src="scripts/app.js" />
But when rendered the browser treats them as "www.mydomain.com/styles/main.css
" rather than "www.mydomain.com/NodeJsApplication1/styles/main.css
".
Update 2
I know of two three possible (non-ideal) solutions to this problem.
- The first being to modify the NodeJS applications to specify a full URL but this requires the application to know the subdirectory that nginx is configured with and it ruins portability to another environment.
- The second is to use subdomains. This I know works and each application could be set as
NodeJsApplication1.mydomain.com
and all links will act as expected. The issue I have with this is it requires setting up a DNS record for each application. I want something that could be almost done automatically without much manual work. (A wildcard record is not appropriate as the domain is used for other purposes). - Use the
<base>
tag to specify the root of the application. Again this has the problem of requiring a change to the application rather than the environment.
Best Answer
I had a similar issue with having multiple MEAN apps on the same domain. I wanted subdirectories instead of having to create a new subdomain for each app. In addition to adding a rewrite to your Nginx config:
You also need to set your
<base>
tag in the head of your index:from https://www.digitalocean.com/community/questions/how-to-run-multiple-node-application-with-nginx-same-droplet-same-domain