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 sort an array in javascript?

What are the SPL Iterators in PHP?

How to pick what array_intersect function to use in PHP?

How to provide a default model object for relationships?

How to use subdomains as parameters in your routes (or in your web.php file)

How to show a specific view file for certain error codes?

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

How to exclude URLs from the Laravel CSRF protection?

How to block an IP address in .htaccess

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