Apache へのアクセスを IP アドレスやヘッダで制限する
Ubuntu 上の Apache へのアクセスを IP アドレスやヘッダを組み合わせた条件で制限する設定方法をメモしておきます。
検証環境
対象 |
バージョン |
Ubuntu |
24.04.2 LTS |
Apache |
2.4.58 |
Apache のインストール
Ubuntu の標準リポジトリから Apache をインストールします。
apt update
apt -y install apache2
今回はバージョン 2.4.58 がインストールされました。 尚、インストール直後の状態で Apache は起動 (active / enabled) していました。
複数条件を設定する
今回はデフォルトの設定ファイルである /etc/apache2/sites-enabled/000-default.conf
に設定を行います。 設定変更後は systemctl restart apache2
を実行して変更を反映します。
OR 条件を設定する
OR 条件は RequireAny ディレクティブを使って設定します。
1
2
3
4
5
6
7
8
9
10
11
12
13
14 | <VirtualHost *:80>
ServerAdmin webmaster@localhost
DocumentRoot /var/www/html
ErrorLog ${APACHE_LOG_DIR}/error.log
CustomLog ${APACHE_LOG_DIR}/access.log combined
<Directory "/var/www/html/">
SetEnvIf access-token "ABCDEF" access_allowed
<RequireAny>
Require env access_allowed
Require ip 10.0.0.99/32
</RequireAny>
</Directory>
</VirtualHost>
|
AND 条件を設定する
AND 条件は RequireAll ディレクティブを使って設定します。
1
2
3
4
5
6
7
8
9
10
11
12
13
14 | <VirtualHost *:80>
ServerAdmin webmaster@localhost
DocumentRoot /var/www/html
ErrorLog ${APACHE_LOG_DIR}/error.log
CustomLog ${APACHE_LOG_DIR}/access.log combined
<Directory "/var/www/html/">
SetEnvIf access-token "ABCDEF" access_allowed
<RequireAll>
Require env access_allowed
Require ip 10.0.0.99/32
</RequireAll>
</Directory>
</VirtualHost>
|
アクセステスト
xh を使ってアクセスするには以下のように実行します。 検証なので結果の表示を「リクエストヘッダ・レスポンスヘッダ」だけに絞り、ボディ表示を省略しています。
xh --print=Hh http://10.0.0.1
ヘッダを付与してアクセスするには以下のように実行します。
xh --print=Hh http://10.0.0.1 "access-token:ABCDEF"
参考
デフォルトの /etc/apache2/sites-enabled/000-default.conf
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29 | <VirtualHost *:80>
# The ServerName directive sets the request scheme, hostname and port that
# the server uses to identify itself. This is used when creating
# redirection URLs. In the context of virtual hosts, the ServerName
# specifies what hostname must appear in the request's Host: header to
# match this virtual host. For the default virtual host (this file) this
# value is not decisive as it is used as a last resort host regardless.
# However, you must set it for any further virtual host explicitly.
#ServerName www.example.com
ServerAdmin webmaster@localhost
DocumentRoot /var/www/html
# Available loglevels: trace8, ..., trace1, debug, info, notice, warn,
# error, crit, alert, emerg.
# It is also possible to configure the loglevel for particular
# modules, e.g.
#LogLevel info ssl:warn
ErrorLog ${APACHE_LOG_DIR}/error.log
CustomLog ${APACHE_LOG_DIR}/access.log combined
# For most configuration files from conf-available/, which are
# enabled or disabled at a global level, it is possible to
# include a line for only one particular virtual host. For example the
# following line enables the CGI configuration for this host only
# after it has been globally disabled with "a2disconf".
#Include conf-available/serve-cgi-bin.conf
</VirtualHost>
|