How do I get the server_name in nginx to use as a

2020-03-31 04:45发布

问题:

I have multiple domain names pointing to the same node server using nginx. The node server needs to know which domain it is running the current request for. How do I pass this information through.

An nginx setup for each domain:

server {

    listen 443;

    ssl on;
    ssl_certificate /etc/letsencrypt/live/mydomain/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/mydomain/privkey.pem;


    server_name mydomain;

    location / {
        proxy_pass http://localhost:3010;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection 'upgrade';
        proxy_set_header Host $host;
        proxy_cache_bypass $http_upgrade;
    }
}

Node runs in upstart but that is probably irrelevant. How do I run node on the command line so that I can pick up mydomain as an environment variable. I currently run as:

NODE_PATH=./src NODE_ENV=production PORT=3010 APIPORT=3012 /node/path/node bin/server.js >> /log/path/mydomain.log 2>&1

回答1:

If you want to pass an environment variable, you'd have to run your node app as:

NODE_PATH=./src NODE_ENV=production SERVER_NAME=servername PORT=3010 APIPORT=3012 /node/path/node bin/server.js >> /log/path/mydomain.log 2>&1

It would be available as process.env.SERVER_NAME but that way you'd have to hardcode the server name. It has to be set up during the start of your Node app and cannot be defined by nginx, because it's not nginx that is starting your Node app.

But instead of passing it as an environment variable you can pass it from nginx as an HTTP header. You can use:

proxy_pass_header Server;

Or if that's not enough, you can use something like:

proxy_set_header ServerName $server_name;

to pass a custom header to Node, and access it - for example in Express:

var serverName = req.header('ServerName');


标签: node.js nginx