.htaccessでURL正規化(wwwあり・なし、https強制、index.html(php)なし)
- 公開日:2019/10/7
.htaccessでURLの正規化をするのに、毎回、以前作ったサイトを確認してコピーしてという作業が面倒になってきたので、自分のためのメモです。
いつも設定するのは以下3つ。
・index.html(htm/php)をなしに統一
・wwwをありに統一、または、なしに統一
・httpsに強制
indexなし、wwwあり、https強制
<IfModule mod_rewrite.c> RewriteEngine On # indexなしに統一 RewriteCond %{THE_REQUEST} ^.*/index.(html|htm|php) RewriteRule ^(.*)index.(html|htm|php)$ https://%{HTTP_HOST}/$1 [R=301,L] # wwwありに統一 RewriteCond %{HTTP_HOST} !^www\.(.*) [NC] RewriteRule ^ https://www.%{HTTP_HOST}/$1 [R=301,L] # httpsに統一 RewriteCond %{HTTPS} off RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L] </IfModule>
indexなし、wwwなし、https強制
最近は(私が依頼をうけて作るサイトは)wwwなしのサイトが増えてきたように思います。
<IfModule mod_rewrite.c> RewriteEngine On # indexなしに統一 RewriteCond %{THE_REQUEST} ^.*/index.(html|htm|php) RewriteRule ^(.*)index.(html|htm|php)$ https://%{HTTP_HOST}/$1 [R=301,L] # wwwなしに統一 RewriteCond %{HTTP_HOST} ^www\.(.*) [NC] RewriteRule ^ https://%1%{REQUEST_URI} [R=301,L] # httpsに統一 RewriteCond %{HTTPS} off RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L] </IfModule>
ドメイン名をべったり書いている例とか見かけますが、個人的にはあまり好きじゃないので上記のようにしています。
あと、たまにRewriteEngine Onを何回も書いているhtaccessを見かける時がありますが、1回でいいです。<IfModule mod_rewrite.c>もWordpressとか入れてると既に記述があったりしますので環境に合わせてください。