禁止使用ip访问页面的方法

需求

今天用户那边抛来一个需求,要求我们的网页页面只能使用域名去访问,而不能使用ip直接访问。一开始也是没啥头绪,后来Google了一下,基本上得到解决这个问题的两个思路,都是从Apache配置上去解决的。

  1. 使用在虚拟主机(VirtualHost)的目录中添加限制,deny掉所有通过ip访问的权限
  2. 启用重定向功能(rewrite),将所有以ip形式访问重定向到另外一个页面上

这里我们使用第二种方法来实现。

实现方法

假设我们的服务器域名为www.example.com,所解析的ip为1.2.4.8。要求是通过www.example.com可以正常访问页面,通过1.2.4.8访问时重定向到一个404页面。

这里我们将会考虑同时使用http/https访问的情况

编辑apache配置文件httpd.conf

vim httpd.conf # 由于apache安装目录不一定统一,这里只显示编辑httpd.conf这个关键文件

<VirtualHost 1.2.4.8:443>                           # 设置虚拟主机
    ServerName 1.2.4.8                              # 设置服务名为1.2.4.8,只有通过1.2.4.8访问时才会执行下面的重定向请求
    DocumentRoot /home/example
    SSLEngine on                                    # 启用ssl,用于https访问
    SSLCertificateFile /home/example/server.crt
    SSLCertificateKeyFile /home/example/server.key
    RewriteEngine On                                # 启用重定向
    RewriteRule  ^.*  /404.html                     # 将请求重定向到页面根目录下的404.html
</virtualhost>

<VirtualHost 1.2.4.8:80>
    ServerName 1.2.4.8
    DocumentRoot /home/example
    RewriteEngine On
    RewriteRule  ^.*  /404.html
</virtualhost>

<virtualhost 1.2.4.8:443>                           # 重新设置虚拟主机
    ServerName  www.example.com                     # 设置服务名为本机域名,正常返回使用域名访问的请求
    DocumentRoot  /home/example
</virtualhost>


<virtualhost 1.2.4.8:80>
    ServerName  www.example.com
    DocumentRoot  /home/example
</virtualhost>

重定向页面404.html代码,这里采用了其他人写的内容

https://blog.csdn.net/ahaotata/article/details/84936263
<html>
    <head>
        <meta charset="UTF-8">

        <link href='//fonts.googleapis.com/css?family=Lato:100' rel='stylesheet' type='text/css'>
        

        <style>
            body {
                margin: 0;
                padding: 0;
                width: 100%;
                height: 100%;
                color: #B0BEC5;
                display: table;
                font-weight: 100;
                font-family: 'Lato';
            }

            .container {
                text-align: center;
                display: table-cell;
                vertical-align: middle;
            }

            .content {
                text-align: center;
                display: inline-block;
            }

            .title {
                font-size: 42px;
                margin-bottom: 40px;
            }
        </style>
    </head>
    <body>
        <div class="container">
            <div class="content">
                <div class="title">404 很抱歉,您查看的页面找不到了!</div>
            </div>
        </div>
    </body>
</html>

之后保存退出,重启程序

service httpd restart

之后进行测试即可,分别使用
http://1.2.4.8
https://1.2.4.8
http://www.example.com
https://www.example.com

正常情况下,通过ip访问时页面已经会被重定向到404.html页面,而通过域名则可以正常访问

标签: none