Nginxでのリバースプロキシ設定ガイド|初心者でも1時間で理解できる構成と実践方法
Nginxでのリバースプロキシ設定完全ガイド|基本から応用まで
NginxはWebサーバーとしてだけでなく、リバースプロキシとしても非常に優秀です。この記事では、Nginxでリバースプロキシを設定する方法について、基本から応用までを1時間程度で学べるように網羅的に解説します。
1. リバースプロキシとは?
- クライアントのリクエストを別のサーバーに中継する仕組み
- ロードバランシング、SSL終端、キャッシュ、セキュリティ向上などに利用される
- APIサーバーやアプリケーションサーバーとの橋渡しに最適
2. Nginxのインストール
sudo apt update
sudo apt install nginx
3. 基本的なリバースプロキシ設定
server {
listen 80;
server_name example.com;
location / {
proxy_pass http://localhost:3000/;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}
}
各ディレクティブの意味
proxy_pass:転送先のURL(http://127.0.0.1:3000 など)proxy_set_header:リクエストヘッダを転送先に伝える
4. 複数のルーティング先を分岐する
location /api/ {
proxy_pass http://api_backend:4000/;
}
location /web/ {
proxy_pass http://frontend_server:8080/;
}
5. ロードバランシングの設定
upstream backend_servers {
server 127.0.0.1:3000;
server 127.0.0.1:3001;
}
server {
location / {
proxy_pass http://backend_servers;
}
}
6. SSL終端(HTTPS対応)
SSLはNginxで終端し、バックエンドとはHTTPで通信:
server {
listen 443 ssl;
server_name example.com;
ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem;
ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem;
location / {
proxy_pass http://localhost:3000/;
}
}
7. キャッシュ設定(静的ファイルの高速化)
location ~* \.(jpg|jpeg|png|gif|ico|css|js)$ {
expires 30d;
access_log off;
}
8. ヘルスチェック(簡易)
location /health {
return 200 'OK';
add_header Content-Type text/plain;
}
9. エラーハンドリング
error_page 502 /custom_502.html;
location = /custom_502.html {
root /usr/share/nginx/html;
}
10. systemdでの操作
sudo systemctl start nginx
sudo systemctl reload nginx
sudo systemctl status nginx
11. トラブルシューティング
- 502 Bad Gateway:バックエンドが落ちてる/接続不可
- 404 Not Found:proxy_passやlocationのパスミス
- Connection refused:DockerやVMでのネットワーク設定見直し
12. セキュリティ対策
13. まとめ
- Nginxのリバースプロキシは構成柔軟で高性能
- ロードバランシングやSSL終端で活躍
- 各種設定を組み合わせて安定したWeb基盤を構築