介紹下在nginx服務器禁止直接通過IP地址訪問網站的方法,以避免別人惡意指向自己的IP,有需要的朋友參考下。
有時會遇到很多的惡意IP攻擊,在Nginx下可以禁止IP訪問。
Nginx的默認虛擬主機在用戶通過IP訪問,或通過未設置的域名訪問,在server的設置里面添加這一行:
復制代碼代碼示例:
listen 80 default;
后面的default參數表示這個是默認虛擬主機。
Nginx 禁止IP訪問這個設置非常有用。
比如別人通過ip或者未知域名訪問你的網站時,希望禁止顯示任何有效內容,可以給他返回500。
目前國內很多機房都要求網站主關閉空主機頭,防止未備案的域名指向過來造成麻煩。
設置:
復制代碼代碼示例:
server {
listen 80 default;
return 500;
}
listen 80 default;
return 500;
}
也可以把這些流量收集起來,導入到自己的網站,只要做以下跳轉設置:
復制代碼代碼示例:
server {
listen 80 default;
rewrite ^(.*) http://www.mydomain.com permanent;
}
listen 80 default;
rewrite ^(.*) http://www.mydomain.com permanent;
}
按照如上設置后,確實不能通過IP訪問服務器了,但是在應該用中出現當server_name后跟多個域名時,其中一個域名怎么都無法訪問,設置如下:
復制代碼代碼示例:
server {
listen 80;
server_name www.example.com example.com
}
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
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;
}
server {
listen 80 default;
server_name _;
server_name www.example.com example.com
return 500;
}
這樣,通過example.com就能訪問服務器了。
以上介紹了nginx服務器中直接通過IP地址訪問網站的方法,希望對大家有所幫助。
