この内容は古いバージョンです。最新バージョンを表示するには、戻るボタンを押してください。
バージョン:8
ページ更新者:atom
更新日時:2026-06-11 07:07:02

タイトル: .htaccessの有効化
SEOタイトル: Apache httpd.conf で .htaccess を有効化する手順 — AllowOverride All、性能影響、Nginx との比較

この記事の要点
  • .htaccess は Apache のディレクトリ単位の設定上書きファイル。デフォルトでは無効化されている
  • 有効化は httpd.conf 内で AllowOverride All (または個別 Options FileInfo AuthConfig 等)
  • 主な用途: mod_rewrite による URL リライト / Basic 認証 / MIME / ヘッダ追加 / アクセス制限
  • 性能影響: 親ディレクトリまで毎リクエストでスキャンするため遅くなる。大規模サイトでは httpd.conf に集約推奨
  • Nginx には .htaccess 相当の機能なしnginx.confconf.d/*.conf を直接編集 → reload
  • 変更後は apachectl configtest で構文チェック → systemctl restart httpd

.htaccess とは

.htaccess (HyperText Access) は Apache HTTP Server が読み込むディレクトリ単位の設定ファイルです。ドキュメントルート以下のフォルダに置くと、そのフォルダと配下に対してhttpd.conf の設定を上書きできます。

共有ホスティングのように個別ユーザに httpd.conf を触らせられない環境で、ユーザが自分のディレクトリだけ設定変更するために考案された仕組みです。

デフォルトで無効な理由

  1. 性能 — リクエスト毎に親ディレクトリを順に .htaccess 探索 → 数百 req/s で無視できない負荷
  2. セキュリティ — ユーザが意図せず認証バイパス・公開設定を書けてしまう
  3. 運用 — 設定が分散して全体像が見えにくくなる

そのため Apache は出荷時に AllowOverride None で .htaccess を完全に無視するのが既定です。これを許可するには明示的な変更が必要です。

有効化の基本: AllowOverride

# /etc/httpd/conf/httpd.conf (RHEL/CentOS)
# /etc/apache2/apache2.conf (Debian/Ubuntu)


    Options Indexes FollowSymLinks
    AllowOverride All           ← ★ ここがポイント
    Require all granted
AllowOverride 値許可する .htaccess 内ディレクティブ
None無効 (.htaccess を読まない / 既定)
All全て許可
AuthConfigBasic / Digest 認証関連 (AuthType, Require)
FileInfomod_rewrite, AddType, Header, RedirectMatch など
IndexesDirectoryIndex, IndexOptions
LimitAllow / Deny / Order (古典)
Options[=…]Options ディレクティブ。Options=FollowSymLinks,ExecCGI のように制限可

本番では All ではなく、必要な機能だけを許可するのがベストプラクティスです。

# 推奨: 認証と mod_rewrite だけ許可

    AllowOverride AuthConfig FileInfo
    Require all granted

反映手順

# 構文チェック (RHEL/CentOS)
sudo apachectl configtest
# または
sudo httpd -t

# Debian/Ubuntu
sudo apache2ctl configtest
sudo apache2ctl -t

# 出力例
# Syntax OK

# サービス再起動
sudo systemctl restart httpd      # RHEL/CentOS
sudo systemctl restart apache2    # Debian/Ubuntu

# graceful (既存コネクションを壊さない)
sudo apachectl graceful
sudo systemctl reload httpd

.htaccess の主な用途

1. mod_rewrite による URL リライト

# /var/www/html/.htaccess
RewriteEngine On

# www あり → www 無しに統一
RewriteCond %{HTTP_HOST} ^www\.example\.com$ [NC]
RewriteRule ^(.*)$ https://example.com/$1 [R=301,L]

# HTTP → HTTPS
RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://%{HTTP_HOST}/$1 [R=301,L]

# クリーン URL を index.php に流す (Laravel / Symfony / WordPress)
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^ index.php [L]

2. Basic 認証

# /var/www/html/admin/.htaccess
AuthType Basic
AuthName "Restricted Area"
AuthUserFile /etc/httpd/htpasswd
Require valid-user

# パスワードファイル作成
# htpasswd -c /etc/httpd/htpasswd alice
# 2 人目以降は -c を外す
# htpasswd /etc/httpd/htpasswd bob

3. IP アドレス制限

# Apache 2.4+

    Require all granted
    Require not ip 203.0.113.45


# または
Require ip 192.0.2.0/24 198.51.100.0/24

# Apache 2.2 の旧構文 (互換用)
Order Deny,Allow
Deny from all
Allow from 192.0.2.0/24

4. レスポンスヘッダ追加 / MIME 設定

# セキュリティヘッダ

    Header set X-Frame-Options "SAMEORIGIN"
    Header set X-Content-Type-Options "nosniff"
    Header set Strict-Transport-Security "max-age=31536000; includeSubDomains"


# キャッシュ

    Header set Cache-Control "max-age=31536000, public"


# MIME 型
AddType application/wasm .wasm
AddType image/avif .avif
AddType font/woff2 .woff2

# gzip 圧縮

    AddOutputFilterByType DEFLATE text/html text/css text/javascript application/json

5. アクセス禁止 (重要ファイル保護)

# .env や .git を公開しない

    Require all denied


# ディレクトリ一覧無効化
Options -Indexes

動作確認

# .htaccess が読まれているか
echo "Test" > /var/www/html/test.html
curl -I http://localhost/test.html
# X-Frame-Options: SAMEORIGIN ← 追加したヘッダが見える

# Apache のエラーログで .htaccess パースエラーを確認
sudo tail -f /var/log/httpd/error_log              # RHEL
sudo tail -f /var/log/apache2/error.log            # Debian

# mod_rewrite が有効か
apachectl -M | grep rewrite
# Debian は a2enmod rewrite で有効化
sudo a2enmod rewrite && sudo systemctl restart apache2

性能への影響

Apache はリクエスト毎にそのファイルパスの全親ディレクトリを順に .htaccess 探索します。/var/www/html/a/b/c/index.php なら最大 4 階層分の stat 呼び出しが発生します。

シナリオ性能影響推奨
共有レンタルサーバ影響小 (元々遅い).htaccess で OK
専用サーバ / VPS の中小規模 (< 100 req/s)誤差レベル.htaccess で OK
本番大規模 (1000 req/s+)5〜30% 低下★ httpd.conf に集約 + AllowOverride None
CMS のテーマで .htaccess 多用必要な設定だけ抜き出して に移植

本番推奨: httpd.conf に集約

# /etc/httpd/conf.d/myapp.conf

    AllowOverride None                  ← .htaccess 無視 (高速)
    Require all granted

    # .htaccess に書いていた内容をここに移植
    RewriteEngine On
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^ index.php [L]

    Header set X-Frame-Options "SAMEORIGIN"



    AuthType Basic
    AuthName "Restricted"
    AuthUserFile /etc/httpd/htpasswd
    Require valid-user

Nginx の場合

Nginx には .htaccess 相当の機能はありません。性能のために意図的に省かれている設計で、設定は nginx.conf/etc/nginx/conf.d/*.conf に直接書きます。

# /etc/nginx/conf.d/myapp.conf
server {
    listen 80;
    server_name example.com;
    root /var/www/html/public;

    # mod_rewrite 相当 (Laravel)
    location / {
        try_files $uri $uri/ /index.php?$query_string;
    }

    # Basic 認証
    location /admin {
        auth_basic           "Restricted";
        auth_basic_user_file /etc/nginx/htpasswd;
    }

    # セキュリティヘッダ
    add_header X-Frame-Options SAMEORIGIN;
    add_header X-Content-Type-Options nosniff;

    # 重要ファイル禁止
    location ~ /\.(?!well-known) { deny all; }
}

# 反映
# sudo nginx -t && sudo systemctl reload nginx

FAQ

Q: .htaccess を置いたのに反映されない
A: 該当ディレクトリの AllowOverrideNone のままです。httpd.conf の対応する ブロックを修正 → systemctl restartapachectl -t -D DUMP_VHOSTS でどの設定が効いているか確認できます。

Q: 「500 Internal Server Error」になる
A: .htaccess の構文エラーが最有力。tail -f /var/log/httpd/error_log でメッセージを確認。RewriteRule の正規表現ミス、AuthUserFile パスの権限不足、未有効モジュールの利用 (mod_rewrite が無効など) が典型です。

Q: WordPress / Laravel のドキュメントが .htaccess 前提
A: 共有ホスティングを想定しているためです。VPS や本番では同じ内容を httpd.conf や Nginx 設定に書き写し、AllowOverride None + .htaccess を読まない運用にするのが性能・セキュリティ両面で有利です。