Apache設定ファイルの書き方と主要ディレクティブまとめ【保存版】

Apache設定ファイルの書き方と主要ディレクティブまとめ【保存版】 apache
Apache(httpd)の設定ファイル(httpd.conf / apache2.conf / conf.d/*.conf / sites-available/*.conf / .htaccess)でよく使うディレクティブを、効果と用途ごとに整理しました。実運用でのベース構成・セキュリティ・パフォーマンス・トラブル時の確認ポイントまで一気に把握できます。 設定ファイルの場所と読み込み順
  • メイン/etc/httpd/conf/httpd.conf(RHEL系) / /etc/apache2/apache2.conf(Debian系)
  • 追加読込conf.d/*.conf / mods-enabled/*.load, *.conf / sites-enabled/*.conf
  • バーチャルホストsites-available/*.confsites-enabled に有効化(Debian系は a2ensite
  • .htaccess:ディレクトリ単位の上書き(AllowOverride 許可が必要)

VirtualHost(サイトごとの設定)

<VirtualHost *:80>
  ServerName example.com
  ServerAlias www.example.com
  DocumentRoot /var/www/example/public
  ErrorLog  ${APACHE_LOG_DIR}/example_error.log
  CustomLog ${APACHE_LOG_DIR}/example_access.log combined

  <Directory "/var/www/example/public">
    Options FollowSymLinks
    AllowOverride All           # .htaccess の使用可否
    Require all granted         # 公開
  </Directory>
</VirtualHost>
  • ServerName:このVHostにマッチするホスト名
  • DocumentRoot:公開ディレクトリ
  • Directory:対象ディレクトリの細かな振る舞い

Directory / Location / Files 系

<Directory "/var/www/example/private">
  Require all denied            # アクセス拒否
</Directory>

<FilesMatch "\.php$">
  Require all granted
</FilesMatch>

<Location "/admin">
  Require ip 192.0.2.0/24       # 管理画面を社内IPに限定
</Location>
  • Require:アクセス制御(all granted/deniediphost
  • OptionsIndexes(一覧表示)、FollowSymLinksExecCGI
  • AllowOverride:.htaccessで上書きできる項目(None 推奨。必要部位のみ All / FileInfo など)

mod_rewrite(URL書き換え)

<IfModule mod_rewrite.c>
  RewriteEngine On
  # HTTP → HTTPS へ統一
  RewriteCond %{HTTPS} !=on
  RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]

  # フロントコントローラ方式(例:Laravel)
  RewriteCond %{REQUEST_FILENAME} !-f
  RewriteCond %{REQUEST_FILENAME} !-d
  RewriteRule ^ index.php [L]
</IfModule>

リダイレクトやSPA/フレームワークのフロントコントローラ構成で多用。順序と条件のマッチに注意。

SSL / TLS(mod_ssl)

<VirtualHost *:443>
  ServerName example.com
  DocumentRoot /var/www/example/public
  SSLEngine on
  SSLCertificateFile      /etc/letsencrypt/live/example.com/fullchain.pem
  SSLCertificateKeyFile   /etc/letsencrypt/live/example.com/privkey.pem

  # 推奨セキュリティ(例)
  SSLProtocol all -SSLv3 -TLSv1 -TLSv1.1
  SSLCipherSuite PROFILE=SYSTEM
  SSLHonorCipherOrder on
</VirtualHost>

Let’s Encrypt を使うなら certbot の自動更新を忘れずに(cron / systemd timer)。

リバースプロキシ(mod_proxy, mod_proxy_http, mod_proxy_fcgi)

# Node/Go 等を後段に
ProxyPass        /app http://127.0.0.1:3000/app
ProxyPassReverse /app http://127.0.0.1:3000/app

# PHP-FPM と連携(拡張子で振り分け)
<FilesMatch "\.php$">
  SetHandler "proxy:unix:/run/php/php8.2-fpm.sock|fcgi://localhost/"
</FilesMatch>

プロキシ利用時は Timeout や後段のヘルスチェック、X-Forwarded-* ヘッダの取り扱いに注意。

HTTPヘッダ(mod_headers)

# セキュリティヘッダ例
Header always set X-Frame-Options "SAMEORIGIN"
Header always set X-Content-Type-Options "nosniff"
Header always set Referrer-Policy "strict-origin-when-cross-origin"
Header always set Content-Security-Policy "default-src 'self'; img-src 'self' data: https:; script-src 'self' 'unsafe-inline' 'unsafe-eval' https:; style-src 'self' 'unsafe-inline' https:"

# キャッシュ制御(静的アセット)
<LocationMatch "\.(css|js|png|jpg|svg|woff2?)$">
  Header set Cache-Control "public, max-age=31536000, immutable"
</LocationMatch>

圧縮(mod_deflate / mod_brotli)

# gzip
AddOutputFilterByType DEFLATE text/html text/plain text/css application/javascript application/json image/svg+xml

# brotli(有効なら優先)
AddOutputFilterByType BROTLI_COMPRESS text/html text/plain text/css application/javascript application/json image/svg+xml

ログ(フォーマットとローテーション)

LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\"" combined
CustomLog ${APACHE_LOG_DIR}/access.log combined
ErrorLog  ${APACHE_LOG_DIR}/error.log
LogLevel warn

障害調査は ErrorLogLogLevel を一時的に debug に上げる。ログ肥大は logrotate で管理。

MPMと接続(パフォーマンス)

  • event / worker(スレッド型):静的配信に強く、リソース効率良い。PHP-FPMと相性◎
  • prefork(プロセス型):古いmod_phpと相性。今は基本的に非推奨
<IfModule mpm_event_module>
  StartServers          2
  ServerLimit          32
  ThreadLimit          64
  ThreadsPerChild      32
  MaxRequestWorkers  1024
  MaxConnectionsPerChild 0
</IfModule>

KeepAlive / タイムアウト

KeepAlive On
MaxKeepAliveRequests 100
KeepAliveTimeout 5
Timeout 60

遅延の大半は後段(アプリ/DB)由来。ここを過剰に伸ばすより、アプリ側の最適化やキュー化を優先。

.htaccess を使うか問題

  • 推奨:可能ならサイトのVHost設定で完結(AllowOverride None)。性能・管理面で有利。
  • やむなし:共有ホスティングやCMS都合なら AllowOverride FileInfo Options など必要最小限で。

よく使うスニペット

www あり/なし統一

RewriteEngine On
RewriteCond %{HTTP_HOST} ^www\.(.+)$ [NC]
RewriteRule ^ https://%1%{REQUEST_URI} [R=301,L]

メンテナンスページ(IP除外)

RewriteEngine On
RewriteCond %{REMOTE_ADDR} !^192\.0\.2\.
RewriteRule ^ /maintenance.html [R=302,L]

ファイル直リンク禁止(画像)

RewriteEngine On
RewriteCond %{HTTP_REFERER} !^$ 
RewriteCond %{HTTP_REFERER} !example\.com [NC]
RewriteRule \.(png|jpe?g|gif|webp)$ - [F,L]

運用チェックリスト

  • [ ] 構文チェック:apachectl configtest / httpd -t
  • [ ] 有効モジュール確認:apachectl -M / a2enmod, a2dismod
  • [ ] ポート待受確認:ListenSSLCertificate の整合
  • [ ] 権限:DocumentRoot とログディレクトリの所有者/権限
  • [ ] 性能:MPM設定、圧縮、キャッシュヘッダ、静的ファイルの期限
  • [ ] セキュリティ:ディレクトリのIndexes無効、管理URLのIP制限、基本ヘッダの追加

主要コマンド(Debian系例)

# サイト/モジュール有効化
sudo a2ensite example.conf
sudo a2enmod rewrite headers ssl proxy proxy_http proxy_fcgi

# 構文チェック & リロード
sudo apachectl configtest
sudo systemctl reload apache2   # 設定のみ反映
sudo systemctl restart apache2  # プロセス再起動

本記事のスニペットはベースラインです。トラフィック量やアプリの特性、OSのセキュリティポリシーに合わせて調整してください。

コメント

タイトルとURLをコピーしました