咱们在使用的时候会遇到不少的恶意IP***,这个时候就要用到Nginx 禁止IP访问了。下面咱们就先看看Nginx的默认虚拟主机在用户经过IP访问,或者经过未设置的域名访问(好比有人把他本身的域名指向了你的ip)的时 候生效最关键的一点是,在server的设置里面添加这一行:服务器
listen 80 default; ide
后面的default参数表示这个是默认虚拟主机。网站
Nginx 禁止IP访问这个设置很是有用。server
好比别人经过ip或者未知域名访问你的网站的时候,你但愿禁止显示任何有效内容,能够给他返回500.目前国内不少机房都要求网站主关闭空主机头,防止未备案的域名指向过来形成麻烦。就能够这样设置:ip
server { 域名
listen 80 default; it
return 500; io
} class
也能够把这些流量收集起来,导入到本身的网站,只要作如下跳转设置就能够:test
server {
listen 80 default;
rewrite ^(.*) http://www.example.com permanent;
}
按照如上设置后,确实不能经过IP访问服务器了,可是在应该用中出现当server_name后跟多个域名时,其中一个域名怎么都没法访问,设置以下:
server {
listen 80;
server_name www.example.com example.com
}
没更改以前,经过server_name 中的www.example.com example.com都可访问服务器,加入Nginx 禁止IP访问的设置后,经过example.com没法访问服务器了,www.example.com能够访问,用 Nginx -t 检测配置文件会提示warning:
[warn]: conflicting server name “example.com” on 0.0.0.0:80,
ignored
the configuration file /usr/local/Nginx/conf/
Nginx.conf syntax is ok
configuration file /usr/local/Nginx/conf/Nginx.
conf test is successful
最后经过在listen 80 default;后再加server_name _;解决,形式以下:
#禁止IP访问
server {
listen 80 default;
server_name _;
server_name www.example.com example.com
return 500;
}
这样,经过example.com就能访问服务器了。