我們就先看看Nginx的默認虛擬主機在用戶通過IP訪問,或者通過未設置的域名訪問(比如有人把他自己的域名指向了你的ip)的時候生效最關鍵的一點是,在server的設置里面添加這一行:
listen 80 default;
后面的default
參數(shù)表示這個是默認虛擬主機。
Nginx 禁止IP訪問這個設置非常有用。
比如別人通過ip或者未知域名訪問你的網站的時候,你希望禁止顯示任何有效內容,可以給他返回500.目前國內很多機房都要求網站主關閉空主機頭,防止未備案的域名指向過來造成麻煩。
就可以這樣設置:
server { listen 80 default; return 500; }
也可以把這些流量收集起來,導入到自己的網站,只要做以下跳轉設置就可以:
server { listen 80 default; rewrite ^(.*) http://www.mydomain.com permanent; }
按照如上設置后,確實不能通過IP訪問服務器了,但是在應該用中出現(xiàn)當server_name
后跟多個域名時,其中一個域名怎么都無法訪問
設置如下:
server { listen 80; server_name www.abc.com abc.com }
沒更改之前,通過server_name 中的www.abc.com abc.com均可訪問服務器,加入Nginx 禁止IP訪問的設置后,通過abc.com無法訪問服務器了,www.abc.com可以訪問,用 Nginx -t
檢測配置文件會提示warning:
[warn]: conflicting server name “abc.com” on 0.0.0.0:80, ignored the configuration file /usr/local/webserver/Nginx/conf/ Nginx.conf syntax is ok configuration file /usr/local/webserver/Nginx/conf/Nginx. conf test is successful
最后通過在listen 80 default;
后再加server_name _;
解決
形式如下:
#禁止IP訪問 server { listen 80 default; server_name _; server_name www.abc.com abc.com return 500; }
這樣,通過abc.com就能訪問服務器了。
總結
好了,以上就是CentOS下Nginx禁止IP訪問的全部內容,希望本文的內容對大家的學習或者工作能帶來一定的幫助,如果有疑問大家可以留言交流,謝謝大家對VEVB武林網的支持。
新聞熱點
疑難解答