简体   繁体   中英

Nginx proxy pass subdomain, node vhost

I have some trouble with nginx proxy_pass redirection on localhost subdomain. I have a domain "domain.com", i want to redirect all request on *.domain.com on *.localhost:9000. Then node handle all request on *.localhost:9000 to the good express app.

On nginx conf when i try the following :

server {
    server_name extranet.domain.com;
    listen 80;
    location / {
       proxy_pass http://extranet.localhost:9000;
    }
}

Request on extranet.domain.com are well redirected to the good express webapp.

With this :

server {
    server_name ~^(.*?)\.domain\.com$;
    listen 80;
    location / {
       proxy_pass http://localhost:9000/$1;
    }
}

Express app running on localhost:9000 handle request /mysubdomainname, which implie that regex is good.

But when i try :

server {
    server_name ~^(.*?)\.domain\.com$;
    listen 80;
    location / {
       proxy_pass http://$1.localhost:9000;
    }
}

All request on *.domain.com return http code 502. Why http://localhost:9000/$1; works and not http://$1.localhost:9000; ? (all subdomain are set in /etc/hosts ).

Thanks in advance. I'm totally lost !

When a host name isn't known at run-time, nginx has to use its own resolver . Unlike the resolver provided by OS, it doesn't use your /etc/hosts file.

Maybe this will give you a hint, I wanted to pass the subdomain from Nginx to an Express app. Here is my code:

nginx.conf

http {

upstream express {
  server localhost:3000;
}

domain.com inside nginx/sites-available

server {

listen 80;
server_name ~^(?<subdomain>.+)\.domain\.com$;

location / {
   proxy_set_header Subdomain $subdomain;
   proxy_set_header Host $host;
   proxy_pass http://express;
 }
}

Express app index.js

var express = require('express');
var app = express();

app.get('/', function (req, res) {
    const subdomain = req.headers.subdomain;
});

app.listen(3000, function () {
  console.log('Example app listening on port 4000!');
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM