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

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

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

サイトのキャプチャ

.htaccess Snippets -GitHub

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

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

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

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

.htaccess.txt

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

.htaccess

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

.htaccessの使い方

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

http://www.yourdomain.com/

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

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

http://www.yourdomain.com/
 
| -- directory1
|    | -- .htaccess
|    | -- directory1/childdirectory1
|    | -- directory1/childdirectory2
|    | -- directory1/childdirectory3
|    |    | -- directory1/childdirectory3/newdirectory1
|    |    | -- directory1/childdirectory3/newdirectory2
|    | -- index.html
| -- directory2
| -- directory3

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

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

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

www有りに変更

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

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

全体をwww有りに変更

全体をwww有りにします。

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

ソース

www無しに変更

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

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

全体をwww無しに変更

全体をwww無しにします。

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]

httpsに変更

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

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

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

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

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

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

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

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

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

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

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

ソース

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

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

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

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

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

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

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

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

Redirect 301 / http://newsite.com/

ソース

クリーンなURL

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

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

ソース

セキュリティの設定

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

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

## Apache 2.2
Deny from all

## Apache 2.4
# Require all denied

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

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

## 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

ソース

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

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

## 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

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

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

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

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

RedirectMatch 404 /\..*$

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

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

<FilesMatch "(\.(bak|config|dist|fla|inc|ini|log|psd|sh|sql|swp)|~)$">
    ## Apache 2.2
    Order allow,deny
    Deny from all
    Satisfy All

    ## Apache 2.4
    # Require all denied
</FilesMatch>

ソース

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

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

Options All -Indexes

hotlinkingを制限

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

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

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

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

htpasswd -c /home/fellowship/.htpasswd boromir

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

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

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

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

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

<Files "one-ring.o">
Require valid-user
</Files>

<FilesMatch ^((one|two|three)-rings?\.o)$>
Require valid-user
</FilesMatch>

パフォーマンスの設定

テキストファイルの圧縮

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

<IfModule mod_deflate.c>

    # Force compression for mangled headers.
    # http://developer.yahoo.com/blogs/ydn/posts/2010/12/pushing-beyond-gzipping
    <IfModule mod_setenvif.c>
        <IfModule mod_headers.c>
            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
        </IfModule>
    </IfModule>

    # Compress all output labeled with one of the following MIME-types
    # (for Apache versions below 2.3.7, you don't need to enable <code>mod_filter</code>
    #  and can remove the <code><IfModule mod_filter.c></code> and <code></IfModule></code> lines
    #  as <code>AddOutputFilterByType</code> is still in the core directives).
    <IfModule mod_filter.c>
        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
    </IfModule>

</IfModule>

ソース

ヘッダの有効期限を設定

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

<IfModule mod_expires.c>
    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"
</IfModule>

ソース

eTagヘッダを利用しない

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

<IfModule mod_headers.c>
    Header unset ETag
</IfModule>
FileETag None

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

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

PHPの変数の設定

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

php_value <key> <val>

# For example:
php_value upload_max_filesize 50M
php_value max_execution_time 240

エラーページの設定

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

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

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

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

<Files *.md>
    ForceType application/octet-stream
    Header set Content-Disposition attachment
</Files>

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

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

<FilesMatch "\.(tex|log|aux)$">
    Header set Content-Type text/plain
</FilesMatch>

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

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

<IfModule mod_headers.c>
    <FilesMatch "\.(eot|otf|ttc|ttf|woff|woff2)$">
        Header set Access-Control-Allow-Origin "*"
    </FilesMatch>
</IfModule>

文字コードをUTF-8に

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

# 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

ソース

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

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

AddHandler application/x-httpd-php55 .php

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

sponsors

top of page

©2024 coliss