2026/06/22(月)nginxで設定をモジュール化して再利用する

投稿日:

PHP-FPMとかの設定がvhostに散らばってて一元化したかったけど/etc/nginx/nginx.conflocationディレクティブを書くと構造上エラーになるため、再利用可能なモジュールと切り出し各vhostの設定から呼び出して解決したログ。

確認環境

  • nginx/1.26.1

やり方の一例

PHP-FPMを設定する例

  1. /etc/nginx/snippetsに適当な名前で.confを作る
    • 例:/etc/nginx/snippets/php-fpm.conf
  2. 作ったファイルに設定を書く
    location ~ ^.+\.php$ {
      fastcgi_pass unix:/var/run/php/php8.3-fpm.sock;
      fastcgi_index index.php;
      include fastcgi_params;
      fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
      fastcgi_param HTTPS on;
      fastcgi_param SERVER_PORT 443;
    }
    
  3. 読み込みたいvhostの.confから参照する

    server {
      listen [::]:443 ssl;
      server_name hoge.example.com;
    
      # ワイルドカード証明の設定も外出ししておくと共通化できて便利
      include snippets/cert.conf;
    
      client_max_body_size 100M;
    
      root /var/www/hoge;
      index index.php;
    
      location / {
        index index.php;
        try_files $uri $uri/ =404;
      }
    
      include snippets/php-fpm.conf;
    
    }