4

Problem

I have a web which works fine on a root domain like mydomain.com without any modification. But if I want to serve it as mydomain.com/app1 I I need to modify the source code in the backend and statics links (css, images, etc) in the html

  • nodejs :
    • from app.get('/') to app.get('/app1')
  • html
    • from src="main.css" to src="app1/main.css"

Question

Should I always modify the application when I want to assign a domain/path using nginx?

Sample app

https://github.com/jrichardsz/nodejs-static-pages/blob/master/server.js

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

Nginx for root domain

This is my nginx configuration which works for mydomain.com

server {
  listen 80;
  server_name mydomain.com;
 
  location / {
    proxy_pass http://localhost:8080/;
  }
}

Attempt for mydomain.com/app1

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.

JRichardsz
  • 14,356
  • 6
  • 59
  • 94

1 Answers1

7

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

Community
  • 1
  • 1
Brad
  • 159,648
  • 54
  • 349
  • 530
  • Thanks Brad. In my case I change localhost to 127.0.0.1 and works with your example. I have another question related to this requirement but with "redirects". Thanks so much!! – JRichardsz Dec 06 '16 at 01:00