route different proxy based on subdomain request in nginx

NginxProxy

Nginx Problem Overview


I have one dedicated server in that server I deployed 5 nodejs application.

domain name: www.nnd.com
dedicated server ip: xxx.xx.x.60

I had domain which is pointed to my dedicated server ip.

sub domains are :

app1.nnd.com pointed to xxx.xx.x.60
app2.nnd.com pointed to xxx.xx.x.60
app3.nnd.com pointed to xxx.xx.x.60
app4.nnd.com pointed to xxx.xx.x.60
app5.nnd.com pointed to xxx.xx.x.60

now in nginx configuration file based on the subdomain I need to route proxy. Example:

{
    listen:80;
    server_name:xxx.xx.x.60
    location / {
        #here based on subdomain of the request I need to create proxy_pass for my node application 
    }
}

Is there any condition and how can I get the original domain name from proxy header?

Nginx Solutions


Solution 1 - Nginx

create a virtual host for each

server {
  server_name sub1.example.com;
  location / {
    proxy_pass http://127.0.0.1:xxxx;
  }
}
server {
  server_name sub2.example.com;
  location / {
    proxy_pass http://127.0.0.1:xxxx;
  }
}

And go on, change the port number to match the right port.

Solution 2 - Nginx

You can use RegExp to fetch host name like this

server {
    server_name   ~^(www\.)?(?<domain>.+)$;

    location / {
        root   /sites/$domain;
    }
}

Solution 3 - Nginx

You can create virtual host for every sub domain.

For Ex you have 2 sub domain abc.xyz.com and abcd.xyz.com , and you want to host it on nginx single instance by proxy_pass then you can simply create virtual host for every sub domain

server {
  server_name abc.xyz.com;
  location / {
    proxy_pass http://127.0.0.1:8000;
  }
}
server {
  server_name abcd.xyz.com;
  location / {
    proxy_pass http://127.0.0.1:8000;
  }
}

For more information you can refer here

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionsridharView Question on Stackoverflow
Solution 1 - NginxMohammad AbuShadyView Answer on Stackoverflow
Solution 2 - NginxChia-Yu PaiView Answer on Stackoverflow
Solution 3 - Nginxabhaygarg12493View Answer on Stackoverflow