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 object has a static variable defined?

How to check if a (blade) view file exists

How to set up custom error pages in .htaccess for your Apache server (ErrorDocument)

How to fix the MySQL related "Specified key was too long error" error in Laravel

How to sort an array of dates and times?

How to access the Laravel's route parameters outside of the controller?

How to return an item in Eloquent, or throw a ModelNotFoundException exception if it isn't found?

How to check if a relation was loaded on an Eloquent model already?

How to make multiple routes share the same URL structure or URL parameters

How to select what columns to return when calling ::all()