Home > Back-end >  why nginx server listen on explicit ip-port cover server listen on only port
why nginx server listen on explicit ip-port cover server listen on only port

Time:10-28

For example, I have a server with 2 network interface, one for public ip and one for private ip. And write 2 nginx configuration file:

cat /etc/nginx/sites-enabled/siteA.sample.edu.cn
server {
  listen 80;
  server_name           siteA.sample.edu.cn;
  ...

  location / {
    root      /var/lib/www/siteA.sample.edu.cn;
    index     index.html index.htm index.php;
  }
}

cat /etc/nginx/sites-enabled/siteB.sample.edu.cn
server {
  listen 80;
  server_name           siteB.sample.edu.cn;
  ...

  location / {
    root      /var/lib/www/siteB.sample.edu.cn;
    index     index.html index.htm index.php;
  }
}

As long as they both listen on 80 without ip restriction, they can work together well. Setting local dns for siteA and siteB with the same ip 172.16.0.1, I can visit different site with those url.

But when setting explict listen ip to one site:

cat /etc/nginx/sites-enabled/siteA.sample.edu.cn
server {
  listen 172.16.0.1:80;
  server_name           siteA.sample.edu.cn;
  ...
  }
}

cat /etc/nginx/sites-enabled/siteB.sample.edu.cn
server {
  listen 80;
  server_name           siteB.sample.edu.cn;
  ...
  }
}

Then I cannot visit siteB.sample.edu.cn anymore. Using url http://siteB.sample.edu.cn will finally reach the siteA.sample.edu.cn.

So how to stop such strange redirection? It seems that server with explicit listen ip has higher priority?

CodePudding user response:

This behaviour is documented here.

You could try using two listen directives in site B's server block.

For example:

server {
  listen 172.16.0.1:80;
  listen 80;
  ...
}

Or:

server {
  listen 172.16.0.1:80;
  listen <otherIP>:80;
  ...
}
  • Related