1.

CentOS Nginx インストール完全ガイド

編集
この記事の要点
  • 基本: sudo dnf install nginx で OS 標準リポジトリ版が入る
  • 最新版が欲しい場合は nginx 公式 yum リポジトリ (nginx.repo) を追加
  • 起動・自動起動: systemctl enable --now nginx
  • Firewalld で HTTP/HTTPS 許可: firewall-cmd --add-service=http --permanent
  • SELinux 有効環境ではポート / ファイルコンテキストに注意。Let's Encrypt + certbot で HTTPS 化

はじめに

Nginx (エンジンエックス) は、Web サーバ・リバースプロキシ・ロードバランサ・HTTP キャッシュとして広く使われる高性能サーバソフトウェアです。イベント駆動アーキテクチャにより Apache prefork より少ないメモリで多接続を捌けます。本記事では CentOS Stream 9 / RHEL 9 / AlmaLinux 9 / Rocky Linux 9 での導入手順を扱います(CentOS 7/8 もほぼ同じ)。

方法 A: OS 標準リポジトリ(dnf)でインストール

# システム更新
sudo dnf update -y

# EPEL リポジトリ追加 (CentOS 7 では必須、9 では既定で入る場合あり)
sudo dnf install -y epel-release

# Nginx インストール
sudo dnf install -y nginx

# バージョン確認
nginx -v
# nginx version: nginx/1.20.1 (RHEL 9 標準)

OS 標準は安定しているがバージョンが古め。最新版が必要なら方法 B へ。

方法 B: nginx 公式 yum リポジトリ

# /etc/yum.repos.d/nginx.repo を作成
sudo tee /etc/yum.repos.d/nginx.repo > /dev/null <<'EOF'
[nginx-stable]
name=nginx stable repo
baseurl=http://nginx.org/packages/centos/$releasever/$basearch/
gpgcheck=1
enabled=1
gpgkey=https://nginx.org/keys/nginx_signing.key
module_hotfixes=true

[nginx-mainline]
name=nginx mainline repo
baseurl=http://nginx.org/packages/mainline/centos/$releasever/$basearch/
gpgcheck=1
enabled=0
gpgkey=https://nginx.org/keys/nginx_signing.key
module_hotfixes=true
EOF

# 既存の dnf 版を削除
sudo dnf remove -y nginx

# stable ブランチからインストール
sudo dnf install -y nginx

# mainline (新機能あり) が欲しい場合
sudo dnf --disablerepo=nginx-stable --enablerepo=nginx-mainline install -y nginx

nginx -v
# nginx version: nginx/1.26.x (stable)

起動と自動起動

# 起動 + OS 起動時自動起動
sudo systemctl enable --now nginx

# 状態確認
sudo systemctl status nginx
# Active: active (running)

# 設定再読込(ダウンタイムなし)
sudo systemctl reload nginx
# または
sudo nginx -s reload

# 設定構文チェック (★ reload 前に必ず実行)
sudo nginx -t
# nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
# nginx: configuration file /etc/nginx/nginx.conf test is successful

# 停止
sudo systemctl stop nginx

Firewalld での HTTP/HTTPS 解放

# 現在の許可サービス確認
sudo firewall-cmd --list-services

# HTTP / HTTPS を許可
sudo firewall-cmd --permanent --add-service=http
sudo firewall-cmd --permanent --add-service=https

# 反映
sudo firewall-cmd --reload

# 確認
sudo firewall-cmd --list-all

# 任意ポートを開く場合
sudo firewall-cmd --permanent --add-port=8080/tcp
sudo firewall-cmd --reload

SELinux 対応

# SELinux モード確認
getenforce
# Enforcing (有効) / Permissive (警告のみ) / Disabled

# Nginx が非標準ディレクトリを参照する場合、コンテキスト設定が必要
sudo dnf install -y policycoreutils-python-utils

# 例: /data/www にコンテンツを置く
sudo semanage fcontext -a -t httpd_sys_content_t '/data/www(/.*)?'
sudo restorecon -Rv /data/www

# Nginx が非標準ポートで listen する場合
sudo semanage port -a -t http_port_t -p tcp 8888

# Nginx からネットワーク接続(リバースプロキシ)する場合
sudo setsebool -P httpd_can_network_connect 1

# SELinux 拒否ログ確認
sudo ausearch -m AVC -ts recent
sudo journalctl -t setroubleshoot

設定ファイル構成

パス役割
/etc/nginx/nginx.confメイン設定
/etc/nginx/conf.d/*.conf分割設定(推奨配置先)
/etc/nginx/default.d/*.confデフォルトサーバ用追加設定 (OS 標準版)
/var/log/nginx/access.logアクセスログ
/var/log/nginx/error.logエラーログ
/usr/share/nginx/html/デフォルトドキュメントルート (OS 標準)
/etc/nginx/html/デフォルトドキュメントルート (公式版)

最小バーチャルホスト設定例

# /etc/nginx/conf.d/example.com.conf
server {
    listen 80;
    listen [::]:80;
    server_name example.com www.example.com;

    root /var/www/example.com/public;
    index index.html index.php;

    access_log /var/log/nginx/example.com.access.log;
    error_log  /var/log/nginx/example.com.error.log;

    location / {
        try_files $uri $uri/ =404;
    }

    # 静的ファイルキャッシュ
    location ~* \.(jpg|jpeg|png|gif|ico|css|js|woff2)$ {
        expires 30d;
        add_header Cache-Control "public, immutable";
    }

    # 隠しファイル拒否
    location ~ /\. {
        deny all;
    }
}

PHP-FPM 連携

# PHP 8.x インストール (Remi リポジトリ経由)
sudo dnf install -y https://rpms.remirepo.net/enterprise/remi-release-9.rpm
sudo dnf module enable php:remi-8.3 -y
sudo dnf install -y php php-fpm php-mysqlnd php-mbstring php-xml php-gd

# 起動
sudo systemctl enable --now php-fpm

# /etc/php-fpm.d/www.conf を編集
# user = nginx
# group = nginx
# listen.owner = nginx
# listen.group = nginx
# /etc/nginx/conf.d/example.com.conf の server ブロック内に追加
location ~ \.php$ {
    fastcgi_pass unix:/run/php-fpm/www.sock;
    fastcgi_index index.php;
    fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
    include fastcgi_params;
}

リバースプロキシ設定

# Node.js / Spring Boot などのバックエンドへ転送
upstream backend {
    server 127.0.0.1:3000;
    keepalive 32;
}

server {
    listen 80;
    server_name api.example.com;

    location / {
        proxy_pass http://backend;
        proxy_http_version 1.1;
        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_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "upgrade";

        proxy_connect_timeout 5s;
        proxy_send_timeout 60s;
        proxy_read_timeout 60s;
    }
}

Let's Encrypt + certbot で HTTPS 化

# certbot インストール
sudo dnf install -y certbot python3-certbot-nginx

# 証明書取得 + Nginx 設定自動書き換え
sudo certbot --nginx -d example.com -d www.example.com

# テストモード (rate limit を消費しない)
sudo certbot --nginx --dry-run -d example.com

# 自動更新タイマー確認
sudo systemctl status certbot-renew.timer
sudo certbot renew --dry-run

# 更新後の自動 reload
# /etc/letsencrypt/renewal-hooks/deploy/reload-nginx.sh を作成
#!/bin/bash
systemctl reload nginx

Apache から Nginx への移行

  • Apache .htaccess は Nginx で動かない → nginx.conf に書き換え
  • RewriteRule は rewrite ディレクティブで対応
  • mod_rewrite, mod_headers, mod_ssl の機能はほぼ Nginx 内蔵
  • 並行運用は Apache: 8080, Nginx: 80 (リバースプロキシ) 構成も可

セキュリティ設定

# /etc/nginx/conf.d/security.conf
# Nginx バージョン非表示
server_tokens off;

# セキュリティヘッダ
add_header X-Frame-Options "SAMEORIGIN" always;
add_header X-Content-Type-Options "nosniff" always;
add_header Referrer-Policy "strict-origin-when-cross-origin" always;
add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;

# HTTP メソッド制限
if ($request_method !~ ^(GET|HEAD|POST|PUT|DELETE|PATCH|OPTIONS)$) {
    return 405;
}

# クライアント最大サイズ
client_max_body_size 50M;

トラブルシューティング

症状原因対処
403 ForbiddenSELinux / 権限不足restorecon, ファイル権限確認
502 Bad Gatewayバックエンド (PHP-FPM 等) 停止systemctl status php-fpm
ポート開かないfirewalld 未許可firewall-cmd --add-service=http
外部から繋がらないクラウド側 SG 未許可EC2 Security Group 等で 80/443 開放
nginx -t でエラー構文ミスエラー行を修正

FAQ

Q: Apache と Nginx、どちらを使うべき?
A: 同時接続数が多い・静的配信・リバースプロキシ用途は Nginx。.htaccess 文化や mod_php 環境に依存している既存システムは Apache。新規は Nginx 推奨。

Q: Stable と Mainline、どちらを入れるべき?
A: 本番は Stable。Mainline は新機能を試したい場合。Stable も十分新しいです (1.26 等)。

Q: Docker で動かしたい
A: docker run -d -p 80:80 nginx で起動可。本番はリバースプロキシをホスト OS、アプリを Docker のパターンが多い。

Q: HTTP/3 (QUIC) を使いたい
A: Nginx 1.25+ で標準サポート。listen 443 quic reuseport; + add_header Alt-Svc で有効化。

編集
Post Share
子ページ

子ページはありません

同階層のページ
  1. インストール (CentOS編)
  2. 起動・停止コマンドとステータスの確認 (CentOS編)
  3. VPSへの導入例
  4. ドキュメントルートの変更方法
  5. phpを動かす際に必要な設定
  6. サブドメインの設定方法

最近更新/作成されたページ