云服务器 ECS Linux 服务器 nginx 禁止空主机头配置

  • A+
所属分类:Linux
高性能企业级服务器首台5折

如果 Nginx 配置了空主机头,那么任意域名解析指向到服务器IP,都可以访问站点,为了防止域名解析恶意指向主机,可以将 Nginx 默认的空主机头禁止,方法是通过修改 Nginx 的主配置文件 nginx.conf ,使其主机头返回错误信息 500

注:Nginx 的配置文件以阿里云的一键安装脚本环境为例,放置在/alidata/server/nginx/conf/nginx.conf

 

  1. 直接屏蔽未绑定域名的虚拟主机访问,返回500错误(这个错误信息可以自定义):
  1. 1
    <span class="pln"><span class="hljs-keyword">server</span> </span>
  2. 1
    <span class="pun">{</span>
  3. 1
    <span class="pln">     <span class="hljs-section">listen</span>  </span><span class="lit"><span class="hljs-number">80</span></span><span class="pun">;</span>
  4. 1
         <span class="kwd"><span class="hljs-keyword">return</span></span> <span class="lit"><span class="hljs-number">500</span></span><span class="pun">;</span>
  5. 1
    <span class="pun">}</span>
  1. 可以做一个URL重写,把访问的流量导入到需要的网站,比如说网站的主页,配置的时候http://www.aliyun.com替换成需要的URL即可:
  1. 1
    <span class="pln"><span class="hljs-keyword">server</span></span>
  2. 1
    <span class="pun">{</span>
  3. 1
    <span class="pln">     <span class="hljs-section">listen</span> </span><span class="lit"><span class="hljs-number">80</span></span> <span class="kwd"><span class="hljs-section">default</span></span><span class="pun">;</span>
  4. 1
    <span class="pln">     <span class="hljs-attribute">rewrite</span> </span><span class="pun"><span class="hljs-regexp">^(.*)</span></span><span class="pln"> http</span><span class="pun">:</span><span class="com">//www.aliyun.com <span class="hljs-literal">permanent</span>;  </span>
  5. 1
    <span class="pun">}</span>
  1. 禁止空主机头的同时也禁止通过IP访问,可以写成:
  1. 1
    <span class="pln"><span class="hljs-keyword">server</span></span>
  2. 1
    <span class="pun">{</span>
  3. 1
    <span class="pln">    listen </span><span class="lit">80</span>  <span class="kwd"><span class="hljs-built_in">default</span></span><span class="pun"><span class="hljs-built_in">;</span></span>
  4. 1
    <span class="pln">    server_name _</span><span class="pun"><span class="hljs-comment">;</span></span>
  5. 1
        <span class="kwd"><span class="hljs-keyword">return</span></span> <span class="lit"><span class="hljs-number">500</span></span><span class="pun">;</span>
  6. 1
    <span class="pun">}</span>

 

这里的配置需要添加到 nginx 主配置文件里,和主配置文件的 server 并列成同一层级,可以参考下图:

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: