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.