Nginx禁止IP直接访问网站

时间:2022-01-25 11:52:03

禁止别人直接通过IP访问网站,在nginx的server配置文件前面加上如下的配置,如果有通过IP直接访问的,直接拒绝连接(需要去掉别的server下的default_server)。

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

如下所示:

# 禁止IP直接访问网站
server {
      listen       80 default_server;
      listen       [::]:80 default_server;
      server_name  _;
      return 444;
}

# zabbix server
server {
         listen  80;
         server_name 123;
         return 301 https://$host$request_uri;
}
server {
         listen  443;
         server_name 123;
         ssl on;
         ssl_certificate       /etc/nginx/cert/zabbix/nginx.crt;
         ssl_certificate_key   /etc/nginx/cert/zabbix/nginx.key;
         ssl_dhparam           /etc/nginx/cert/zabbix/dhparams.pem;
         ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
         ssl_ciphers 'ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-AES256-GCM-SHA384:DHE-RSA-AES128-GCM-SHA256:DHE-DSS-AES128-GCM-SHA256:kEDH+AESGCM:ECDHE-RSA-AES128-SHA256:ECDHE-ECDSA-AES128-SHA256:ECDHE-RSA-AES128-SHA:ECDHE-ECDSA-AES128-SHA:ECDHE-RSA-AES256-SHA384:ECDHE-ECDSA-AES256-SHA384:ECDHE-RSA-AES256-SHA:ECDHE-ECDSA-AES256-SHA:DHE-RSA-AES128-SHA256:DHE-RSA-AES128-SHA:DHE-DSS-AES128-SHA256:DHE-RSA-AES256-SHA256:DHE-DSS-AES256-SHA:DHE-RSA-AES256-SHA:AES128-GCM-SHA256:AES256-GCM-SHA384:AES128-SHA256:AES256-SHA256:AES128-SHA:AES256-SHA:AES:CAMELLIA:DES-CBC3-SHA:!aNULL:!eNULL:!EXPORT:!DES:!RC4:!MD5:!PSK:!aECDH:!EDH-DSS-DES-CBC3-SHA:!EDH-RSA-DES-CBC3-SHA:!KRB5-DES-CBC3-SHA';
         ssl_prefer_server_ciphers on;
         ssl_session_cache shared:SSL:20m;
         ssl_session_timeout 180m;

         location / {
            root /usr/share/zabbix/;
            index index.php index.html;
        }
         location ~ \.php$ {
            root /usr/share/zabbix/;
            fastcgi_pass 127.0.0.1:9000;
            fastcgi_index index.php;
            fastcgi_param SCRIPT_FILENAME /usr/share/zabbix/$fastcgi_script_name;
            include fastcgi_params;
       }
}