How to force SSL in Apache's .htaccess?

Apache: How to force SSL in Apache's .htaccess?

If you need to enable SSL (https) URLs in htaccess (redirect non SSL to SSL, or redirect http to https in .htaccess) then you should use this code:

  1. RewriteCond %{HTTPS} !=on
  2. RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

If you want to redirect to https AND force www then you can use the following code:

  1. RewriteCond %{HTTP_HOST} ^www\.(.+)$ [NC]
  2. RewriteRule ^(.*)$ https://%1/$1 [R=301,L]

Don't forget that you will probably need to enable the rewrite engine for these rules to work. Click the button below to find out how to do this.

webdevetc profile pic
webdevetc

I am a 29 year old backend web developer from London, mostly focusing on PHP and Laravel lately. This (webdevetc.com) is my blog where I write about some web development topics (PHP, Laravel, Javascript, and some server stuff). contact me here.



More...


Comments and discussion about How to force SSL in Apache's .htaccess?

Found this interesting? Maybe you want to read some more in this series?

Or see other topics in the Apache language

Or see other languages/frameworks:
PHP Laravel Composer Apache CentOS and Linux Stuff WordPress General Webdev and Programming Stuff JavaScript
Or see random questions

How to eager load multiple levels of relationships in Eloquent?

How to output (echo/print) content in PHP

How to namespace a Laravel route group?

How to find the 2nd most common item in an array?

What is Bubble sort, and how to write an implementation of it in PHP

How to get the last character of a string in JS?

How to find the index of a value in an array in JS?

How to block IPv6 IP addresses in .htaccess

What is snake case?

How to check if a (blade) view file exists