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 hide directory listing in .htaccess?

How to eager load multiple levels of relationships in Eloquent?

How to block an IP range based on CIDR in Apache with .htaccess

How to get a route to directly show a view?

How to return JSON data to the user in Laravel?

How to increment a value in the database

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

When is __destruct called in PHP?

What is the difference between empty(), isset(), != null, is_null() in PHP

How to make Apache force download of files (in .htaccess)