nginx reverse proxy redirecting to wrong domain

2019-08-15 06:29发布

问题:

I'm using this tutorial nginx reverse proxy tutorial to setup a node site with nginx. this is what my nano /etc/nginx/conf.d/mydomain.com.conf looks like

server { 
listen 80;
server_name mydomain.com;
location / { 
proxy_pass http://localhost:3000; 
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; 
} 
}

The problem is that when I visit my domain, it's redirecting to another domain that I have setup on the same server. I setup that other domain (a static page) using an nginx virtual hosts tutorial that uses server blocks. One difference I noticed is that the nginx reverse proxy tutorial doesn't do any of this symlinking between sites available and sites enabled which the virtual hosts tutorial does with the server blocks files. The virtual hosts tutorial instructs the reader to create server block files and then enable them like this

sudo ln -s /etc/nginx/sites-available/demo /etc/nginx/sites-enabled/demo

Do I have to do anything to enable the config file when setting up a reverse proxy with nginx? If not, do you know why it's redirecting to the other domain?

/etc/nginx/conf.d/mydomain.com.conf

回答1:

Let me start with a small explanation on how nginx matches the hosts, quoting from how nginx processes a request

In this configuration nginx tests only the request’s header field “Host” to determine which server the request should be routed to. If its value does not match any server name, or the request does not contain this header field at all, then nginx will route the request to the default server for this port.

According to your description I would say there's 2 possibilities,

  1. either that this reverse proxy virtual host has a wrong name, so it's not matched and the request is directed to the first virtual host that listens on port 80.
  2. the reverse proxy is correct but the configuration was not loaded.

To fix this double check that this line is correct server_name mydomain.com; and indeed matches the URL you are requesting, then make sure you reloaded nginx settings sudo service nginx reload



回答2:

The problem was that /etc/nginx/conf.d/mydomain.com.conf hadn't been copied into

/etc/nginx/sites-enabled


标签: node.js nginx