WEBサイトの挙動を司る「.htaccess」の設定メモ

2015年3月1日

.htaccess Tips

サーバー運用をしていて、apache.confに書いてスマートに運用できると一番いいのだが、単一サービスだけを行っているサーバーであれば、問題ないが、.htaccessファイルでディレクトリ単位の管理が行えるのは非常に便利で柔軟性が高い。 デメリットとしては、高負荷の際には、上限値がサーバー制限値よりも下回ってしまうので、低めの閾値で管理することをおすすめする。 いきなりサイト管理者から、「Basic認証かけてよ。」とか言われた時ように、メモっておきます。

Sample

パスワード認証(Basic認証)

「.htpasswd」ファイルを作成。暗号化されたパスワードを記述して任意の場所に設置 # .htaccess [.htpasswdはroot階層からのpathを記述] deny from all AuthUserFile /home/hoge/.htpasswd AuthGroupFile /dev/null AuthName "Please enter your ID and password" AuthType Basic require valid-user # .htpasswd [guest,hogeの2つのユーザーを登録] guest:3/H1Ec7SRPVQA hoge:$apr1$dTCYavDQ$i75ufSwLF/yH0v5m/l0ZL0

アクセス制限

# 「1.1.1.1」「2.2.2.*」「example.com」からのアクセスを禁止する order allow,deny allow from all deny from 1.1.1.1 deny from 2.2.2. deny from example.com #リファラで判別して禁止する(example.com以外のリファラを禁止) SetEnvIf Referer "://www\.example\.com" ok_url # UA判別して禁止する(IE以外を禁止) SetEnvIf User-Agent "MSIE" ok_ua order deny,allow deny from all allow from env=ok_ua # robot-searchを制限する(hoge-bot.comからのアクセスを禁止) SetEnvIf User-Agent "hoge-bot.com" ng_ua order allow,deny allow from all deny from env=ng_ua # 特定のファイルをアクセス不可にする(例はjsonファイル) Deny from all # 特定のファイルをアクセス不可且つ、特定のアクセスのみ許容する Order allow,deny Allow from 192.168.1.1/24 Deny from all

リダイレクト

# サイト全体のリダイレクト RedirectMatch 301 .* http://example.com/ # ルート階層のリダイレクト Redirect permanent / http://example.com/ # ディレクトリ単位のリダイレクト Redirect permanent /hoge/ http://example.com/hoge/ # スマホなどのUA判別 RewriteEngine On RewriteBase / RewriteCond %{REQUEST_URI} !^mobile/.*$ RewriteCond %{HTTP_USER_AGENT} iPhone [NC,OR] RewriteCond %{HTTP_USER_AGENT} iPod [NC,OR] RewriteCond %{HTTP_USER_AGENT} BlackBerry [NC,OR] RewriteCond %{HTTP_USER_AGENT} Android.*Mobile [NC,OR] RewriteCond %{HTTP_USER_AGENT} Windows\ Phone [NC,OR] RewriteCond %{HTTP_USER_AGENT} Windows\ CE [NC] RewriteCond %{HTTP_USER_AGENT} !iPad [NC] RewriteRule ^(.*)$ mobile/$1 [R,L]

ファイル一覧表示の設定

# 禁止 Options -Indexes # 許可 Options Indexes

Errorページの表示設定

# 401 [パスワード認証エラー] ErrorDocument 401 /error/401.html # 403 [権限エラー] ErrorDocument 403 /error/403.html # 404 [File not found] ErrorDocument 404 /error/404.html # 500 [CGIプログラムエラー] ErrorDocument 500 /error/500.html #Caution 別セグメントディレクトリに設置しないと、飛んだ先で同一のエラーが出ていた場合は、無限ループになる可能性があるので、要注意!

デフォルトページの設定

# 複数登録でき、優先順位をつけられる DirectoryIndex index.php index.html hoge.html

Site

http://htaccess.cman.jp/

このブログを検索

ごあいさつ

このWebサイトは、独自思考で我が道を行くユゲタの少し尖った思考のTechブログです。 毎日興味がどんどん切り替わるので、テーマはマルチになっています。 もしかしたらアイデアに困っている人の助けになるかもしれません。