Home > Blockchain >  How to make nginx process only the specified host (alocal, blocal), but ignore the "naked"
How to make nginx process only the specified host (alocal, blocal), but ignore the "naked"

Time:12-19

I have two rules for nginx (local):

server_name alocal;
listen 80; 
location / {
    ...
    proxy_pass http://localhost:8081;
}

and

server_name blocal;
listen 80; 
location / {
    ...
    proxy_pass http://localhost:8082;
}

I also changed the "hosts" file.

C:\Windows\System32\Drivers\etc\hosts


127.0.0.1             alocal
127.0.0.1             blocal

Everything works well. When I make a request through the browser, I get the expected behavior.

http://alocal -> http://127.0.0.1:8081
http://blocal -> http://127.0.0.1:8082

But when I specify just "localhost" as a host, nginx still processes my request, and it takes the first rule that comes along (from those that I gave above).

http://localhost -> http://127.0.0.1:8081
or (depends on which rule comes first)
http://localhost -> http://127.0.0.1:8082
  1. Why does nginx process localhost if other hosts (alocal, blocal) are specified in server_name?

  2. How to make nginx process only the specified host (alocal, blocal), but ignore the "naked" ip address?

CodePudding user response:

Nginx listening to Port 80. If there is a request not matching any server_name the default is taken. Either given by listen 80 default_server; or the first entry if omitted. If you want to block all requests not matching the specified server_name or with empty Host-Header you need a catch all as last block:

server {
    listen      80 default_server;
    server_name "";
    return      444;
}

It will be not really ignored, but rejected. You can't "ignore" something, nginx is blocking port 80 and handling all requests somehow.

  • Related