
もくじ
.htaccessを用いたURLの正規化について
「URLの正規化」とは、同一ページのURLを統一する為の対策です。
例えば、index.htmlの有り無しやwww有り無しなどです。
↓
https://example.com/
https://example.com/index.html
https://www.example.com/
https://www.example.com/index.html
https://example.com/index.html
https://www.example.com/
https://www.example.com/index.html
これらの4つのURLは同じページを指していますよね。
でも、何の対策していなければユーザーによって「https://example.com/」へアクセスしたり「https://example.com/index.html」へアクセスしたりと、アクセスするURLがバラバラになってしまいます。
そうなると、同一ページなのにGoogleの評価が分散されてしまう可能性も出てきます。
また、http://~とhttps://~が混在するのも同様に良くないですよね。
そこで、今回はいずれかのURLへ統一するための.htaccessの記述方法をまとめておきます。
と言っても、最近の流れからすると「https://example.com/」の形に統一するのが一般的だとは思いますが。
index.htmlやindex.phpをスラッシュ終わりに統一
- index.htmlをスラッシュ終わりに統一
RewriteEngine On
RewriteCond %{THE_REQUEST} ^.*/index.html
RewriteRule ^(.*)index.html$ http://example.com/$1 [R=301,L]
RewriteCond %{THE_REQUEST} ^.*/index.html
RewriteRule ^(.*)index.html$ http://example.com/$1 [R=301,L]
- index.phpをスラッシュ終わりに統一
RewriteEngine On
RewriteCond %{THE_REQUEST} ^.*/index.php
RewriteRule ^(.*)index.php$ http://example.com/$1 [R=301,L]
RewriteCond %{THE_REQUEST} ^.*/index.php
RewriteRule ^(.*)index.php$ http://example.com/$1 [R=301,L]
- index.html、index.phpをまとめてスラッシュ終わりに統一
RewriteEngine On
RewriteCond %{THE_REQUEST} ^.*/index.(html|php)
RewriteRule ^(.*)index.php$ http://example.com/$1 [R=301,L]
RewriteCond %{THE_REQUEST} ^.*/index.(html|php)
RewriteRule ^(.*)index.php$ http://example.com/$1 [R=301,L]
wwwあり、なしを統一
- wwwなしに統一
RewriteEngine on
RewriteCond %{HTTP_HOST} ^www\.sample\.com
RewriteRule ^(.*)$ http://example.com/$1 [R=301,L]
RewriteCond %{HTTP_HOST} ^www\.sample\.com
RewriteRule ^(.*)$ http://example.com/$1 [R=301,L]
- wwwありに統一
RewriteEngine on
RewriteCond %{HTTP_HOST} ^example\.com
RewriteRule ^(.*)$ http://www.example.com/$1 [R=301,L]
RewriteCond %{HTTP_HOST} ^example\.com
RewriteRule ^(.*)$ http://www.example.com/$1 [R=301,L]
「http://~」へのアクセスを「https://~」へ統一
今では、「http://~」へのアクセスは「https://~」へリダイレクトさせて統一させるのが一般的になってきました。
いわゆる「常時SSL化(SSL通信を強制化)」の設定と同じ内容になります。
#SSL通信設定
RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]
RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]