Nginx 禁止IP訪問

咱們在使用的時候會遇到不少的惡意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就能訪問服務器了。

相關文章
相關標籤/搜索