ブログやサイトのパフォーマンス改善やセキュリティ向上のためによく使う.htaccessの設定のまとめ

ブログやWebサイトのパフォーマンスの改善やSEO、セキュリティの向上に役立つ.htaccessの設定を紹介します。

ドメインをwww有り・無しに統一、新ドメインに引っ越した時のリダイレクト、URLをクリーンなものにしたり、共有サーバーでのPHPのバージョンを指定したりなど、すぐに利用できるものばかりです。

サイトのキャプチャ

.htaccess Snippets -GitHub

元記事には有用な.htaccessのスニペットがPublic Domainでまとめられおり、それら全部に加えて.htaccessファイルの作成と使い方を加えました。

.htaccessファイルの作成と使い方

「.htaccess」ファイルを作成することは非常に簡単です。
テキストベースのアプリケーションを開き、ワードラップ機能をオフにしてコードを記述し、ファイルを保存します。

Windowsのメモ帳などを使用すると保存する際、ファイル名に「.txt」が加わってしまいます。

[text]
.htaccess.txt
[/text]

これは問題ありません。
ファイルをアップロードした後、サーバー上でリネームします。

[text]
.htaccess
[/text]

ファイルをアップロードする際は、ASCIIモードで行い、パーミッションは「644」にします。
共有サーバーなどでは「604(グループ不可)」の場合もあるので、システム管理者やサーバー会社へ確認してください。

.htaccessの使い方

「.htaccess」ファイルは設置されたディレクトリとその配下にある全てのディレクトリに影響を与えます。つまり、ルートに「.htaccess」ファイルを設置した場合は、全てのフォルダに影響を与えます。

[text]
http://www.yourdomain.com/

| -- .htaccess
| -- directory1
| -- directory2
| -- directory3
| | -- directory3/childdirectory1
| | -- directory3/childdirectory2
| -- index.html
[/text]

ルートではなく、一つ下の「directory1」に設置するとどうなるでしょうか?
この場合は「directory1」とその配下のフォルダのみに限定されます。
「directory2」「directory3」には適用されません。

[text]
http://www.yourdomain.com/

| -- directory1
| | -- .htaccess
| | -- directory1/childdirectory1
| | -- directory1/childdirectory2
| | -- directory1/childdirectory3
| | | -- directory1/childdirectory3/newdirectory1
| | | -- directory1/childdirectory3/newdirectory2
| | -- index.html
| -- directory2
| -- directory3
[/text]

.htaccesを編集する時の注意点

「.htaccess」ファイルを編集する時は、万が一に備えてバックアップをとるようにしましょう。
また、編集の際はコメントで簡単な説明(用途や日時)を加えることを勧めます。
「#」を使用すると、その行がコメントになります。

リライトとリダイレクトの設定

www有りに変更

「www無しのURL」を「www有りのURL」へ向け直し、www有りにします。

[text]
RewriteEngine on
RewriteCond %{HTTP_HOST} ^example\.com [NC]
RewriteRule ^(.*)$ http://www.example.com/$1 [L,R=301,NC]
[/text]

全体をwww有りに変更

全体をwww有りにします。

[text]
RewriteCond %{HTTP_HOST} !^$
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteCond %{HTTPS}s ^on(s)|
RewriteRule ^ http%1://www.%{HTTP_HOST}%{REQUEST_URI} [R=301,L]
[/text]

ソース

www無しに変更

「www有りのURL」を「www無しのURL」へ向け直し、www無しにします。

[text]
RewriteEngine on
RewriteCond %{HTTP_HOST} ^www\.example\.com [NC]
RewriteRule ^(.*)$ http://example.com/$1 [L,R=301]
[/text]

全体をwww無しに変更

全体をwww無しにします。

[text]
RewriteEngine on
RewriteCond %{HTTP_HOST} ^www\.
RewriteCond %{HTTPS}s ^on(s)|off
RewriteCond http%1://%{HTTP_HOST} ^(https?://)(www\.)?(.+)$
RewriteRule ^ %1%3%{REQUEST_URI} [R=301,L]
[/text]

httpsに変更

httpへのアクセスをhttpsに向け直します。

[text]
RewriteEngine on
RewriteCond %{HTTPS} !on
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI}
[/text]

httpsに変更(プロキシの場合)

プロキシサーバーを経由している場合の設定。

[text]
RewriteCond %{HTTP:X-Forwarded-Proto} !https
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI}
[/text]

最後にスラッシュを加える

リクエストがあったURIの最後にスラッシュを加えます。

[text]
RewriteCond %{REQUEST_URI} /+[^\.]+$
RewriteRule ^(.+[^/])$ %{REQUEST_URI}/ [R=301,L]
[/text]

シングルページのリダイレクト

ページを指定したURIにリダイレクトします。

[text]
Redirect 301 /oldpage.html http://www.yoursite.com/newpage.html
Redirect 301 /oldpage2.html http://www.yoursite.com/folder/
[/text]

ソース

シングルディレクトリのエイリアス

ディレクトリのエイリアスを設定します。

[text]
RewriteEngine On
RewriteRule ^source-directory/(.*) target-directory/$1
[/text]

スクリプトへのエイリアスパス

ディレクトリ内のどんなリクエストも「index.fcgi」にします。

[text]
RewriteEngine On
RewriteRule ^$ index.fcgi/ [QSA,L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.fcgi/$1 [QSA,L]
[/text]

サイト全体をリダイレクト

「oldsite.com/some/link.html」を「newsite.com/some/link.html」に向け直します。

[text]
Redirect 301 / http://newsite.com/
[/text]

ソース

クリーンなURL

「.php」などファイルの拡張子は開発者にとっては有用かもしれません。しかし、サイトのビジターにとっては絶対ではありません。下記の記述はPHPファイルから「.php」を削除します。これは「.html, .asp」など他の拡張子でも利用できます。

[text]
RewriteEngine On
RewriteCond %{SCRIPT_FILENAME} !-d
RewriteRule ^([^.]+)$ $1.php [NC,L]
[/text]

ソース

セキュリティの設定

ファイルへのアクセスを制限

全ファイルへのアクセスを拒否します。

[text]
## Apache 2.2
Deny from all

## Apache 2.4
# Require all denied
[/text]

自分以外ファイルへのアクセスを制限

自分以外の全ファイルへのアクセスを拒否します。
「xxx.xxx.xxx.xxx」には自分のIPアドレスを入れてください。

[text]
## Apache 2.2
Order deny,allow
Deny from all
Allow from xxx.xxx.xxx.xxx

## Apache 2.4
# Require all denied
# Require ip xxx.xxx.xxx.xxx
[/text]

ソース

指定IPアドレスのみファイルへのアクセスを制限

指定IPアドレスの全ファイルのアクセスを拒否します。
「xxx.xxx.xxx.xxx」には拒否するIPアドレスを入れてください。

[text]
## Apache 2.2
Order deny,allow
Allow from all
Deny from xxx.xxx.xxx.xxx
Deny from xxx.xxx.xxx.xxy

## Apache 2.4
# Require all granted
# Require not ip xxx.xxx.xxx.xxx
# Require not ip xxx.xxx.xxx.xxy
[/text]

非表示ファイルとディレクトへのアクセスを制限

「.htaccess, .htpasswd, .git」など非表示にしたいファイルやディレクトリへのアクセスを拒否します。

[text]
RewriteCond %{SCRIPT_FILENAME} -d [OR]
RewriteCond %{SCRIPT_FILENAME} -f
RewriteRule "(^|/)\." - [F]
[/text]

攻撃された際に手がかりを与えないために、エラーを返すとよいでしょう。

[text]
RedirectMatch 404 /\..*$
[/text]

バックアップやソースファイルへのアクセスを制限

バックアップや設定などのソースファイルへのアクセスを拒否します。

[text]

## Apache 2.2
Order allow,deny
Deny from all
Satisfy All

## Apache 2.4
# Require all denied

[/text]

ソース

ディレクトリ一覧を表示させない

index.htmlがない場合、ディレクトリ一覧が表示されてしまうのを禁止します。

[text]
Options All -Indexes
[/text]

hotlinkingを制限

hotlinkingとはあなたのサイトの画像を他の誰かに勝手に利用されてしまうことで、自分のドメイン以外で画像が呼び出されること禁止します。

[text]
RewriteEngine on
RewriteCond %{HTTP_REFERER} !^$
RewriteCond %{HTTP_REFERER} !^http(s)?://(www\.)?yourdomain.com [NC]
RewriteRule \.(jpg|jpeg|png|gif)$ - [NC,F,L]
[/text]

ディレクトリをパスワードで保護

まずはパスワードを記述した「.htpasswd」ファイルを作成します。

[text]
htpasswd -c /home/fellowship/.htpasswd boromir
[/text]

保護するディレクトにBasic認証を設定します。

[text]
AuthType Basic
AuthName "One does not simply"
AuthUserFile /home/fellowship/.htpasswd
Require valid-user
[/text]

一つあるいは複数のファイルをパスワードで保護

一つあるいは複数のファイルにBasic認証を設定します。

[text]
AuthName "One still does not simply"
AuthType Basic
AuthUserFile /home/fellowship/.htpasswd


Require valid-user


Require valid-user

[/text]

パフォーマンスの設定

テキストファイルの圧縮

テキストファイルをgzip圧縮します。

[text]

# Force compression for mangled headers.
# http://developer.yahoo.com/blogs/ydn/posts/2010/12/pushing-beyond-gzipping


SetEnvIfNoCase ^(Accept-EncodXng|X-cept-Encoding|X{15}|~{15}|-{15})$ ^((gzip|deflate)\s*,?\s*)+|[X~-]{4,13}$ HAVE_Accept-Encoding
RequestHeader append Accept-Encoding "gzip,deflate" env=HAVE_Accept-Encoding

# Compress all output labeled with one of the following MIME-types
# (for Apache versions below 2.3.7, you don't need to enable mod_filter
# and can remove the and lines
# as AddOutputFilterByType is still in the core directives).

AddOutputFilterByType DEFLATE application/atom+xml \
application/javascript \
application/json \
application/rss+xml \
application/vnd.ms-fontobject \
application/x-font-ttf \
application/x-web-app-manifest+json \
application/xhtml+xml \
application/xml \
font/opentype \
image/svg+xml \
image/x-icon \
text/css \
text/html \
text/plain \
text/x-component \
text/xml


[/text]

ソース

ヘッダの有効期限を設定

ページで使用しているCSS, JSをはじめ、フォントや画像などの有効期限を設定します。CSSやJSファイルのバージョンをファイル名でコントロールしないのであれば、「1 week」にすることも検討してください。

[text]

ExpiresActive on
ExpiresDefault "access plus 1 month"

# CSS
ExpiresByType text/css "access plus 1 year"

# Data interchange
ExpiresByType application/json "access plus 0 seconds"
ExpiresByType application/xml "access plus 0 seconds"
ExpiresByType text/xml "access plus 0 seconds"

# Favicon (cannot be renamed!)
ExpiresByType image/x-icon "access plus 1 week"

# HTML components (HTCs)
ExpiresByType text/x-component "access plus 1 month"

# HTML
ExpiresByType text/html "access plus 0 seconds"

# JavaScript
ExpiresByType application/javascript "access plus 1 year"

# Manifest files
ExpiresByType application/x-web-app-manifest+json "access plus 0 seconds"
ExpiresByType text/cache-manifest "access plus 0 seconds"

# Media
ExpiresByType audio/ogg "access plus 1 month"
ExpiresByType image/gif "access plus 1 month"
ExpiresByType image/jpeg "access plus 1 month"
ExpiresByType image/png "access plus 1 month"
ExpiresByType video/mp4 "access plus 1 month"
ExpiresByType video/ogg "access plus 1 month"
ExpiresByType video/webm "access plus 1 month"

# Web feeds
ExpiresByType application/atom+xml "access plus 1 hour"
ExpiresByType application/rss+xml "access plus 1 hour"

# Web fonts
ExpiresByType application/font-woff2 "access plus 1 month"
ExpiresByType application/font-woff "access plus 1 month"
ExpiresByType application/vnd.ms-fontobject "access plus 1 month"
ExpiresByType application/x-font-ttf "access plus 1 month"
ExpiresByType font/opentype "access plus 1 month"
ExpiresByType image/svg+xml "access plus 1 month"

[/text]

ソース

eTagヘッダを利用しない

CSS/JSや画像などをキャッシュする際に更新日時やファイルサイズを付与するeTagヘッダを削除します。

[text]

Header unset ETag

FileETag None
[/text]

ソース
※eTag削除は、元ソースで賛否両論あります。

その他のいろいろ有用な設定

PHPの変数の設定

PHPの変数(アップロードの最大サイズやタイムアウト時間など)をセットします。

[text]
php_value

# For example:
php_value upload_max_filesize 50M
php_value max_execution_time 240
[/text]

エラーページの設定

404などのエラーページに任意のファイルを指定します。

[text]
ErrorDocument 500 "Houston, we have a problem."
ErrorDocument 401 http://error.yourdomain.com/mordor.html
ErrorDocument 404 /errors/halflife3.html
[/text]

ファイルをダウンロードできるようにする

指定した拡張子のファイルを表示する代わりに、ダウンロードするように設定します。

[text]

ForceType application/octet-stream
Header set Content-Disposition attachment

[/text]

ファイルをダウンロードできないようにする

指定した拡張子のファイルをダウンロードする代わりに、表示するように設定します。

[text]

Header set Content-Type text/plain

[/text]

クロスドメインのフォントを許可

CDNサーバーのWebフォントはCORSが原因で、FirefoxやIEで機能しないかもしれません。その場合の対策方法です。

[text]


Header set Access-Control-Allow-Origin "*"


[/text]

文字コードをUTF-8に

文字コードをUTF-8に指定します。
拡張子ごとに設定することも可能です。

[text]
# Use UTF-8 encoding for anything served text/plain or text/html
AddDefaultCharset utf-8

# Force UTF-8 for a number of file formats
AddCharset utf-8 .atom .css .js .json .rss .vtt .xml
[/text]

ソース

PHPのバージョンに特定のものにする

共有サーバーを利用している時など、PHPのバージョンが複数の場合があります。利用するPHPのバージョンを特定のものにします。

[text]
AddHandler application/x-httpd-php55 .php

# Alternatively, you can use AddType
AddType application/x-httpd-php55 .php
[/text]

sponsors

top of page

©2026 coliss