Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set up .htaccess to redirect HTTP to HTTPS equivalent?

I’m using Dreamhost and have secure hosting and a secure certificate. I’m trying to redirect a plain HTTP site to an HTTPS site. I’m a bit confused about doing it.

I want to make http://www.example.com/ redirect to https://www.example.com/

What do I put in what file to make it work?

like image 518
Barreston Robinson Avatar asked Dec 14 '15 00:12

Barreston Robinson


1 Answers

This should work. While you indicate .htaccess the concept is connected to Apache rewrite rules:

RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI}

Just place that in your .htaccess file and all non-HTTPS requests will be directed to the HTTPS.

The way you can test this is to use curl like this; of course change http://www.example.com to match your actual domain name/host name.:

curl -I -L http://www.example.com

The -I flag tells curl just to send back headers and the -L tells curl to follow redirects. If you have that .htaccess setup correctly, then you will see the first hop to the non-HTTPS site and then a redirect—managed by the .htaccess rewrite rules—sending it to the next hop on the HTTPS site.

301 versus 302 redirects.

Just one small note regarding server response messages and potential SEO stuff: When you use that final Apache rewrite rule as pictured, the default server response code would be:

HTTP/1.1 302 Found

A 302 HTTP response is considered a temporary redirect. If you absolutely, positively always want plain-HTTP traffic to go to the HTTPS equivalent on the same server, you should be sending out a 301 HTTP response which is a permanent redirect. To use that Apache rewrite rule to send a 301 code, just tweak the last line so it all looks like this:

RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]

After doing that the response should be:

HTTP/1.1 301 Moved Permanently

And all should be good. But—and not to jump down a weird rabbit hole—Google seems to understand that most people mistakenly send 302 headers when they mean 301, so it seems—according to this article—Google factors in 302 redirects plus some kind of time range. And if you send enough 302s over a certain period of time Google will infer the change is permanent and treat that 302 as a 301.

Slightly confusing but at the end of the day, if you mean to make a redirect permanent, then always set 301 response headers to make everyone’s life easier.

like image 58
Giacomo1968 Avatar answered Sep 21 '22 23:09

Giacomo1968