Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use custom location or path instead root for several apps using nginx?

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.

like image 519
JRichardsz Avatar asked Mar 10 '23 11:03

JRichardsz


1 Answers

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

like image 144
Brad Avatar answered Apr 24 '23 21:04

Brad