Nginx restrict domains

2019-03-29 07:59发布

问题:

Please find the below setting which is placed in /etc/nginx/sites-enabled under my site domain name. (mysite.lk)

server {  
   listen   80;
   server_name mysite.lk www.mysite.lk;

   location / {  
        proxy_set_header   X-Forwarded-For $remote_addr;
        proxy_set_header   Host $http_host;
        proxy_pass "http://127.0.0.1:8080";
   }

} 

The application is running on port 8080 and here I'm redirecting all the 80 traffic to 8080. My website only uses mysite.lk and www.mysite.lk domain names.

Hence, I want to restrict/block all other domains (except mysite.lk and www.mysite.lk) which are coming to this server IP. What is the change that I need to do to achieve this?

I tried numerous things such as answers given in the Why is nginx responding to any domain name?, but was getting errors at the nginx startup.

Please help me out! Thanks.

Update

Found the Answer. A catch-all server block should needed in the top of the config before the given config like below. The code block should be like this.

server {
    return 403;
}

server {
    listen   80;
    server_name mysite.lk www.mysite.lk;
    location / {
        proxy_set_header   X-Forwarded-For $remote_addr;
        proxy_set_header   Host $http_host;
        proxy_pass "http://127.0.0.1:8080";
   }

}

回答1:

The first server defined in Nginx is treated as the default_server so by just adding one as the default and returning 412 (Precondition Failed) or any another status that best fits your requirements, will help for the subsequent servers to obey the server_name

server {
    listen 80 default_server;
    listen [::]:80 default_server;
    server_name _;
    return 412;
} 

server {
    listen   80;
    server_name mysite.lk www.mysite.lk;
    location / {
        proxy_set_header   X-Forwarded-For $remote_addr;
        proxy_set_header   Host $http_host;
        proxy_pass "http://127.0.0.1:8080";
   }
}


回答2:

How about creating a server directive without server_name. Something like this

server {
    listen 80 default_server;

    location / {
        deny all;
    }
}

EDIT Please read http://nginx.org/en/docs/http/request_processing.html In short nginx always looks for best match when it comes to server_names or locations and if it fails to find one it uses the default server.



标签: nginx