炊きたてのご飯が食べたい

定時に帰れるっていいね。自宅勤務できるっていいね。子どもと炊きたてのご飯が食べられる。アクトインディでは積極的にエンジニアを募集中です。

( Apache ) htaccessファイルでサイトのメンテナンス画面を表示 【RewriteCond】


メンテナンス画面を表示する際には、
【1】サイト訪問者をメンテナンス画面にリダイレクト
【2】検索クローラーのキャッシュを除外し、 503 HTTPステータスコード(サービス利用不可)を返す
の2点を考慮しなければいけません。
今回は、サイトのメンテナンスを行う際の .htaccess 設定についてメモします。
【1】サイト訪問者をメンテナンス画面にリダイレクト
(1-1) メンテナンス画面 /maintenance/index.html を作成し、サーバにアップ
メンテナンス画面
(1-2) メンテナンスを表示したいディレクトリに、以下の .htaccessファイルを設置
.htaccess

RewriteEngine On
RewriteCond %{REMOTE_ADDR} !=192.168.0.2
RewriteCond %{REQUEST_URI} !=/maintenance/503.php
RewriteCond %{REQUEST_URI} !\.css$
RewriteCond %{REQUEST_URI} !\.js$
RewriteCond %{REQUEST_URI} !\.jpg$
RewriteCond %{REQUEST_URI} !\.gif$
RewriteCond %{REQUEST_URI} !\.png$
RewriteCond %{REQUEST_URI} !\.swf$
RewriteRule ^.*$ /maintenance/503.php [L]

※RewriteCond %{REMOTE_ADDR} !=192.168.0.2 作業するPCのIPアドレスを記述しておくと、メンテナンス画面にリダイレクトされず、通常画面を表示できる
※画像や外部ファイルの読み込みまでリダイレクトされないように、「RewriteCond %{REQUEST_URI} !\.拡張子css、js)$」を記述
【2】検索クローラーのキャッシュを除外し、 503 HTTPステータスコードを返す
(2-1) /maintenance/index.htmlが検索クローラーにキャッシュされないよう、robot.txt に以下の内容を追記
●robot.txt

User-Agent: *
Disallow: /maintenance/

(2-2) 503 HTTPステータスコードを返し、/maintenance/index.html の内容を表示する /maintenance/503.php を配置
●503.php

[php]<?php header ('HTTP/1.0 503 Service Temporarily Unavailable'); readfile(dirname(FILE) . '/index.html'); ?>[/php]

以上でメンテナンスページの表示が完了です。
メンテナンスを解除するには、.htaccessファイルを削除するか、.htaccess内の記述をコメントアウトしてください。
.htaccessの他の参照記事】
( Apache ) htaccessでリダイレクト設定 【RedirectPermanent】