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 check if a (blade) view file exists

Why should you update APP_URL from from http://localhost?

How to replace values in a string, in JS

How to set infinite execution time in a PHP script

How to create random numbers in JS?

How to find the average value of items in a Laravel Collection?

How does PHP compare objects?

What is WordPress default Apache .htaccess rules?

How to review blog posts (written by other users) before they get published on your WordPress blog?

How to do comments in Blade files?