今天要在Nginx上设置禁止通过IP访问服务器,只能通过域名访问,这样做是为了避免别人把未备案的域名解析到自己的服务器IP而导致服务器被断网,从网络上搜到以下解决方案
我们在使用的时候会遇到很多的恶意IP攻击,这个时候就要用到Nginx 禁止IP访问了。下面我们就先看看Nginx的默认虚拟主机在用户通过IP访问,或者通过未设置的域名访问(比如有人把他自己的域名指向了你的ip)的时 候生效最关键的一点是,在server的设置里面添加这一行:
listen 80 default;
后面的default参数表示这个是默认虚拟主机。
Nginx 禁止IP访问这个设置非常有用。
比如别人通过ip或者未知域名访问你的网站的时候,你希望禁止显示任何有效内容,可以给他返回500.目前国内很多机房都要求网站主关闭空主机头,防止未备案的域名指向过来造成麻烦。就可以这样设置:
简单直接的修改方法:
修改nginx.conf 文件
修改成
<code>server {</code>
<code>listen 80;</code>
<code>server_name www.xcn.cn; </code><code>#这里是你自己指定的域名</code>
<code>...</code>
<code>}</code>
再在上个server后继续添加一段:
就是为了访问默认网站直接返回403
<code>server {</code>
<code>listen 80 default_server;</code>
<code>server_name _;</code>
<code>return</code> <code>403;</code>
<code>}</code>
这里是在接收到ip访问或非指定域名访问时会返回403错误
下面的一些比较详细的介绍:
<code>server { </code>
<code> </code><code>listen 80 default; </code>
<code> </code><code>return</code> <code>500; </code>
<code> </code><code>}</code>
也可以把这些流量收集起来,导入到自己的网站,只要做以下跳转设置就可以:
<code> </code><code>rewrite ^(.*) http:</code><code>//www</code><code>.xcn.cn permanent; </code>
按照如上设置后,确实不能通过IP访问服务器了,但是在应该用中出现当server_name后跟多个域名时,其中一个域名怎么都无法访问,设置如下:
<code> </code><code>listen 80; </code>
<code> </code><code>server_name xcn.cn </code>
[warn]: conflicting server name “xcn.cn” 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 _;解决,形式如下:
<code>#禁止IP访问 </code>
<code>server </code>
<code>{ </code>
<code>listen 80 default; </code>
<code>server_name _; </code>
<code>return</code> <code>500; </code>
或者
<code>listen 80 dufault; </code>
<code>rewrite ^(.*) http:</code><code>//www</code><code>.xcn.cn permanent; </code>
<code> </code><code>server { </code>
<code> </code><code>server_name _; </code>
这样,通过xcn.cn就能访问服务器了。
第一种情况:访问A站定向到B站
<code>server_name www.xcn.cn ; </code>
<code>rewrite ^(.*) http:</code><code>//www</code><code>.xcn.cn$1 permanent; </code>
第二种情况:不是访问A站的全部重定向到指定页面
<code>server_name www.xcn.cn; </code>
<code>if</code> <code>($host != </code><code>'jb51.net'</code><code>) { </code>
<code>rewrite ^/(.*)$ http:</code><code>//www</code><code>.xcn.cn/$1 permanent; </code>
<code>} </code>
如果写在第一个server段
使用IP访问时也将被重定向
本文转自 baishuchao 51CTO博客,原文链接:http://blog.51cto.com/baishuchao/1940183