Nginx禁止IP或非指定域名访问

为了避免别人把未备案的域名恶意解析到自己的服务器IP而导致服务器被断网,需要在Nginx上设置禁止通过IP或其他域名访问服务器。只能通过绑定的指定域名访问
一、只需在server配置文件中添加如下配置
1)80端口的配置
server {
listen 80 default;
server_name _;
rewrite 444;
}
#以上为屏蔽IP/非指定域名访问返回错误444配置
#
#以下为正常配置
#test1.orcy.net.cn 和 test2.orcy.net.cn 可以正常访问
server {
listen 80 ;
server_name test1.orcy.net.cn;
location / {
root html;
index index.html;
}
}
server {
listen 80;
server_name test2.orcy.net.cn;
root html/test2;
index index.html;
}
说明:通过非指定域名访问,将根据规则返回错误444
,也可以设置其他,如502、403、404等,或者跳转其他页面,将 rewrite 444;
替换为rewrite ^(.*) http://test1.orcy.net.cn permanent;
2)443端口的配置
443端口配置和80端口一致,但需要添加证书路径(任意证书均可)
server {
#禁止非绑定域名或IP访问443端口
listen 443 ssl;
server_name _;
return 444; #返回错误444,也可返回502、404等
#开启SSL需要添加证书路径,任意证书均可
ssl_certificate cert/orcy_net_cn.pem; #将domain name.pem替换成您证书的文件名
ssl_certificate_key cert/orcy_net_cn.key; #将domain name.key替换成您证书的密钥文件名
ssl_session_timeout 5m;
ssl_ciphers ECDHE-RSA-AES128-GCM-SHA256:ECDHE:ECDH:AES:HIGH:!NULL:!aNULL:!MD5:!ADH:!RC4; #使用此加密套
ssl_protocols TLSv1 TLSv1.1 TLSv1.2; #使用该协议进行配置
ssl_prefer_server_ciphers on;
error_page 497 301 https://$http_host$request_uri;
}
server {
#此处省略正常配置
}
3)其他端口配置
其他非80/443端口,按照80/443配置模板简单修改即可,开启SSL的配置证书路径即可,否则nginx会报错,提醒server没有证书。
二、重启Nginx或者重载配置
1)重启Nginx
./nginx -s stop
./nginx
2)Nginx重载配置
./nginx -s reload
三、测试结果
如下图,非指定域名访问直接返回错误444

发表评论