Friday, April 19, 2024

禁止通过IP地址直接访问Web服务For Apache/Nginx

如果你的服务器或者网站能够通过IP地址直接访问,那么恶意的第三方可以通过他的一个随便的域名指向你的ip,每次访问该域名都可以正常打开网站,尽管这个页面是你的。这样,如过对方域名没有备案,那么你的IP就被列入黑名单了。

本文讲解如何设置web服务器不可以直接通过IP地址进行访问web服务,必须使用设定的域名访问web服务。

 

1. Httpd/Apache

apache 配置此操作还是比较方便,因为 httpd 的默认的主机是配置文件中第一个VirtualHost,所以把第一虚拟主机作为 403 forbidden 的响应更为合适(此前这个默认的是主web服务器)。

修改配置文件如下:

NameVirtualHost *:80

<VirtualHost xxx.xxx.xxx.xxx:80>

ServerName xxx.xxx.xxx.xxx

DocumentRoot /xxx/xxx

<Directory /xxx/xxx >

Order Allow,Deny
Deny from all

</Directory>

</VirtualHost>

–或者—————-

NameVirtualHost *:80

<VirtualHost *:80>
ServerName xxx.xxx.xxx.xxx
<Location / >
Order Allow,Deny
Deny from all
</Location>
</VirtualHost>

两种表示方式一样,第二种方式简单些,不用指定路径了。关键是把第一个虚拟机的服务名字设定为 ip 地址
2. Nginx
nginx 的设定和httpd类似,都是第一个服务器作为默认的服务器,除非明确指定某个服务器的状态为 default

server {
listen       80 default;
server_name  _;

location / {
root   html;
index  403.html;
}
location ~ /.ht {
deny  all;
}
}

有时我们并不希望客户端收到403的禁止信息,可能404更有迷惑性,则可以如下设置:

server {
listen       80 default;
server_name  _;

location / {
root   html;
#index  403.html;

return 404;
}
location ~ /.ht {
deny  all;
}
}

3. 判定设置是否生效:

[root@test ]# wget http://xxx.xx.xxx.11

–11:07:17–  http://xxx.xx.xxx.11/

Connecting to xxx.xx.xxx.11:80… connected.

HTTP request sent, awaiting response… 403 Forbidden

11:07:17 ERROR 403: Forbidden.

[root@test ]# wget http://xxx.xx.xxx.22

–11:06:46–  http://xxx.xx.xxx.22/

Connecting to xxx.xx.xxx.22:80… connected.

HTTP request sent, awaiting response… 400 Bad Request

11:06:46 ERROR 400: Bad Request.

OK

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.