Movatterモバイル変換


[0]ホーム

URL:


コリス

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

サイト構築 -制作

Post on:2015年2月18日

sponsorsr

ブログや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 onRewriteCond %{HTTP_HOST} ^example\.com [NC]RewriteRule ^(.*)$ http://www.example.com/\ [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 onRewriteCond %{HTTP_HOST} ^www\.example\.com [NC]RewriteRule ^(.*)$ http://example.com/\ [L,R=301]

全体をwww無しに変更

全体をwww無しにします。

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

httpsに変更

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

RewriteEngine onRewriteCond %{HTTPS} !onRewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI}

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

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

RewriteCond %{HTTP:X-Forwarded-Proto} !httpsRewriteRule (.*) 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.htmlRedirect 301 /oldpage2.html http://www.yoursite.com/folder/

ソース

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

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

RewriteEngine OnRewriteRule ^source-directory/(.*) target-directory/\

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

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

RewriteEngine OnRewriteRule ^$ index.fcgi/ [QSA,L]RewriteCond %{REQUEST_FILENAME} !-fRewriteCond %{REQUEST_FILENAME} !-dRewriteRule ^(.*)$ index.fcgi/\ [QSA,L]

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

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

Redirect 301 / http://newsite.com/

ソース

クリーンなURL

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

RewriteEngine OnRewriteCond %{SCRIPT_FILENAME} !-dRewriteRule ^([^.]+)$ $1.php [NC,L]

ソース

セキュリティの設定

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

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

## Apache 2.2Deny from all## Apache 2.4# Require all denied

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

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

## Apache 2.2Order deny,allowDeny from allAllow 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.2Order deny,allowAllow from allDeny from xxx.xxx.xxx.xxxDeny 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} -fRewriteRule "(^|/)\." - [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 onRewriteCond %{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 BasicAuthName "One does not simply"AuthUserFile /home/fellowship/.htpasswdRequire valid-user

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

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

AuthName "One still does not simply"AuthType BasicAuthUserFile /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 50Mphp_value max_execution_time 240

エラーページの設定

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

ErrorDocument 500 "Houston, we have a problem."ErrorDocument 401 http://error.yourdomain.com/mordor.htmlErrorDocument 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/htmlAddDefaultCharset utf-8# Force UTF-8 for a number of file formatsAddCharset utf-8 .atom .css .js .json .rss .vtt .xml

ソース

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

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

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

sponsors

Related Posts

top of page

  • ワードプレステンプレート

Sponsors

  • Eagle
  • ソースネクスト
  • Kindle Unlimited 3ヵ月がなんと0円

    3ヵ月0円の申込期間は、7/14まで

  • 広告掲載募集中
coliss

Recnet Entry

Pickup Entry

Recommend

top of page

Category

Blog Info

当サイトではCookieを使用しています。引き続き当サイトを閲覧することにより、ポリシーを受け入れたものとみなされます。
©2025 coliss

[8]
ページ先頭

©2009-2025 Movatter.jp