Nginxの仮想ホスト設定について説明します。
1. Nginx仮想ホスト
1.1 複数のIPアドレスを使用する場合
設定ファイルを編集します。
server {
listen 80;
server_name 192.168.15.7;
location / {
root /opt/Super_Marie;
index index.html;
}
}
server {
listen 80;
server_name 172.16.1.7;
location / {
root /opt/tank;
index index.html;
}
}
1.2 複数のポートを使用する場合
設定ファイルを編集します。
server {
listen 80;
server_name 192.168.15.7;
location / {
root /opt/Super_Marie;
index index.html;
}
}
server {
listen 81;
server_name 192.168.15.7;
location / {
root /opt/tank;
index index.html;
}
}
1.3 複数のドメインを使用する場合
設定ファイルを編集します。
server {
listen 80;
server_name www.game.com;
location / {
root /opt/Super_Marie;
index index.html;
}
}
server {
listen 80;
server_name www.game1.com;
location / {
root /opt/tank;
index index.html;
}
}
2. Nginxログ
- サイトのステータスコードが500の割合
- サイトへのアクセス元
- トラブルシューティング
Nginxサービスの状態を確認:
systemctl status nginx -l
エラーログのパス:
cat /var/log/nginx/error.log
同じディレクトリにアクセスログがあります。
2.1 Nginxログの変数
- $remote_addr: クライアントIPアドレス
- $http_x_forwarded_for: 実際のクライアントIPアドレス(リバースプロキシで有効)
- $remote_user: JWT認証後のユーザー名
- $time_local: アクセス時間
- $time_iso8601: アクセス時間
- $request: アクセスデータ(リクエストタイプ、パス、HTTPタイプ)
- $body_bytes_sent: アクセス中のデータサイズ
- $status: アクセスステータス(例:404, 304, 200)
- $http_referer: アクセス元のドメイン
- $http_user_agent: クライアントブラウザの識別情報
3. Nginxアクセス制御モジュール
3.1 ngx_http_access_module
- 特定のIPからのアクセスを許可または拒否
- deny: 拒否
- allow: 許可
3.1.1 ケース1: 特定のIPのみ許可
allow 192.168.15.1;
deny all;
3.1.2 ケース2: 特定のネットワーク範囲のみ許可
allow 192.168.15.0/24;
deny all;
3.1.3 ケース3: VPNからのみアクセス許可
allow 172.16.1.81;
deny all;
3.2 ngx_http_auth_basic_module
- アクセス前に認証が必要
3.2.1 ユーザー名とパスワードファイルの作成
yum install httpd-tools -y
htpasswd -c /etc/nginx/auth chenyang
3.2.2 Nginx設定に追加
auth_basic "ログインしてください";
auth_basic_user_file /etc/nginx/auth;
3.2.3 Nginx再起動
nginx -t
systemctl restart nginx
3.3 ngx_http_autoindex_module
- ディレクトリインデックスを表示
autoindex on;
autoindex_exact_size on;
autoindex_localtime on;
autoindex_format json;
4. Nginxステータスモニタリングモジュール
Nginxの実行状態をモニタリングします。
server {
listen 80;
server_name 192.168.15.7;
location / {
stub_status;
}
}
5. 接続制御モジュール
5.1 接続数の制限
5.1.1 abテストコマンドのインストール
yum install httpd-tools -y
5.1.2 abパラメータ
- -n: アクセス総数
- -c: 同時アクセス数
5.1.3 設定ファイル編集
limit_conn_zone $remote_addr zone=addr:10m;
server {
listen 80;
server_name 192.168.15.7;
limit_conn addr 1;
location / {
root /opt/Super_Marie;
index index.html;
}
}
5.2 アクセス数の制限
5.2.1 接続プールの設定
limit_req_zone $remote_addr zone=one:10m rate=1r/s;
5.2.2 ケース1: 1秒あたり1回のアクセスに制限
limit_req_zone $remote_addr zone=one:10m rate=1r/s;
server {
listen 80;
server_name 192.168.15.7;
limit_req zone=one burst=5;
location / {
root /opt/Super_Marie;
index index.html;
}
}