WordPressでhttpをhttpsにリダイレクトする方法

概要

WordPressをhttpをhttpsにリダイレクトする方法です。事前にSSL/TLS対応が必要です。

 

.htaccessの記述

① root権限でターミナルにログインし、WordPressのインストールディレクトリに移動します。

cd /var/www/html

 

② .htaccessファイルのバックアップを取得します。

cp -p .htaccess .htaccess.bak.yyyymmdd

 

③ .htaccessファイルを編集します。

vim .htaccess

 

・ 修正前

# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>
# END WordPress

 

・ 修正後 (# BEGIN WordPressの前に記述する)

<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]
</IfModule>

# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>
# END WordPress

 

設定の解説
RewriteCond URL書き換えを行うルール条件を指定
(RewriteRuleの前に記述)
%{HTTPS} off httpsが無効の場合
R=301 301 – Moved Permanently (恒久的に移転)
リクエストされたリソースの URL が永遠に変更されたことを示し、レスポンスで新しい URLを与える。
「R」はリダイレクトの略
[L] URL書き換え処理を中止し、以降は書き換えを行わない

 

WordPressの設定

・ WordPress管理画面「一般」をクリックし、WordPressアドレス(URL)とサイトアドレス(URL)をhttpからhttpsに変更します。

 

・グレーアウトして設定の変更ができない場合は、wp-config.phpの編集で以下のコードの追加が必要です。

vim /var/www/html/wp-config.php
## URL
define('WP_HOME','https://サイトドメイン/');
define('WP_SITEURL','https://サイトドメイン/');