NGINX : multiple node js applications on same serv

2019-04-11 14:19发布

Problem

If I have some node js apps and if I want publish it as mydomain.com/app1, mydomain.com/app2, etc I have to change the app.get '/' to app.get('/app1' and also in some cases css,js and images paths.

Question

Should you always modify the application when you want to assign a domain/path?

Is there any way to make the application independent?

Is a nodejs or nginx configuration?

This is an node js app used as example :

https://github.com/jrichardsz/responsive_web1.1/blob/master/server.js

This is my nginx configuration for my node js app for mydomain.com (works!)

server {
  listen 80;
  server_name mydomain.com;

  location / {
    proxy_pass http://localhost:8080/;
  }
}

Node app :

app.get('/', function(req, res) {
    // ejs render automatically looks in the views folder
    res.render('index');
});

This is my nginx configuration for the same node js app but mydomain.com/app1 (works!)

server {
  listen 80;
  server_name mydomain.com;

  location /app1/ { 
    proxy_pass http://localhost:8080/app1/; 
  }
}

And this is the fix in node js app

app.get('/app1', function(req, res) {
    // ejs render automatically looks in the views folder
    res.render('index');
});

I tried :

https://github.com/expressjs/express-namespace

http://expressjs.com/en/4x/api.html

But in both cases, I need change my node js app.

Thanks in advance.

标签: node.js nginx
1条回答
唯我独甜
2楼-- · 2019-04-11 15:02

Should you always modify the application when you want to assign a domain/path?

No, you shouldn't have to modify the application at all.

When you use proxy_pass in this manner, you need to rewrite the URL with regex. Try something like this:

  location ~ ^/app1/(.*)$ { 
    proxy_pass http://localhost:8080/$1$is_args$args; 
  }

See also: https://serverfault.com/q/562756/52951

查看更多
登录 后发表回答