.htaccess:httpからhttpsへリダイレクト

.htaccess:httpからhttpsへリダイレクト

author : koki

publish date :

フォームなどをhttpsで公開する場合などで、httpへアクセスされた際にhttpsへリダイレクトさせたい事があると思います。 .htaccessでのリダイレクトとJavaScriptでのリダイレクト方法をご紹介します。

可能であれば.htaccessでの設置がお勧めですが、状況によっては.htaccessを設置できない場合もあると思うのでJavaScriptでのリダイレクト方法を書いておきます。

.htaccess

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

JavaScript

<script type="text/javascript">
(function(){
	if(document.domain.indexOf('example.com') > -1){
		var protocol = 'https:';
		if(location.protocol != protocol){
			location.href = protocol + '//' + document.domain + location.pathname;
		}
	}
})();
</script>
<script type="text/javascript">
(function(){
	if(document.domain.indexOf('example.com') > -1){
		var protocol = 'http:';
		if(location.protocol != protocol){
			location.href = protocol + '//' + document.domain + location.pathname;
		}
	}
})();
</script>

良き開発ライフを!