Raul Lopez
TechSEO

TechSEO

Redirecting from HTTP to HTTPS

Redirecting from HTTP to HTTPS

Raul Lopez's photo
Raul Lopez

Published on Jan 6, 2021

7 min read

Subscribe to my newsletter and never miss my upcoming articles

One of the main problems we may have on Google is called duplicate content. Basically, Google will crawl your website using your internal links, but also the links found on other websites to your site. If one of those links is to your HTTP version we may be facing a duplicate content issue.

Also, Google announced in 2014 that HTTPS was going to be a ranking factor, so we better have it correctly setup!

There are several ways to fix this, but they all fall into two categories:

  • Perform an 301 redirection from the non-HTTPS version to the HTTPS version.
  • Use a canonical tag to indicate Google that the HTTPS version is your preferred one.

The canonical tag is beyond the scope of this article, but you may read more about it here.

What is a 301 redirection?

Basically, it's a way of telling web browsers and crawlers that the content that was previously in a URL is now in some other URL.

In terms of HTTP requests, this would be a standard request to learn.techseo.blog/my-url from a client browser:

GET /my-url HTTP/1.1
Host: techseo.blog

And this would be the response of the web server with a redirection:

HTTP/1.1 301 Moved Permanently
Location: https://learn.techseo.blog/my-url

As you can see, the server responds with a 301 code, which tells the browser to redirect the user to the provided Location.

This should be the behavior of your site when receiving any HTTP request. Not only because of SEO but also to protect users when they are visiting your site.

How to redirect to the HTTPS version using PHP

This first example will use plain PHP to detect if a certain request is not using HTTPS, and will perform the required redirect:

<?php
/**
    Returns a boolean indicating if the current request is using HTTPS or not.
    @return boolean
*/
function isHttps () {
    return (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') || $_SERVER['SERVER_PORT'] == 443;
}

if (!isHttps()) {
    $httpsUrl = 'https://' . $_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
    header('Location: ' . $httpsUrl, true, 301);
    exit; // Don't forget to stop the script execution for a faster redirect
}

// ...

This function isHttps() will check if the $_SERVER variable has HTTPS setup, or if the connection is using the 443 port, which is the port for HTTPS connections.

Finally, this code should be always required so we can make sure that all our HTTP links are being redirected to the HTTPS version.

How to redirect to the HTTPS version using Laravel

Laravel makes forcing redirects much easier for PHP developers. First of all, we need to create a new Middleware:

$ php artisan make:middleware RedirectToHttps

Once we have created our middleware, we will check if the current request is not secure and redirect the user to the secure version in that case.

<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Support\Facades\App;

class RedirectToHttps
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        if (!$request->secure() && app()->isProduction()) {
            return redirect()->secure($request->getRequestUri());
        }

        return $next($request);
    }
}

We are also checking if the app is running in production to avoid performing the redirection on your localhost in case you don't have any SSL certificate installed on your local environment.

How to redirect to the HTTPS version using Express on NodeJS

ExpressJS also makes it super easy to redirect from HTTP to HTTPS in just a few lines of code:

app.use (function (req, res, next) {
    if (req.secure) {
        // secure request
        next();
    } else {
        // insecure request -> we redirect to https
        res.redirect('https://' + req.headers.host + req.url);
    }
});

How to redirect to the HTTPS version using Django

As almost-always, Python has the simplest answer of all languages. To redirect to the HTTPS version using Django you just need to set the following variable inside your settings.py file:

SECURE_SSL_REDIRECT = True

And that's it with Django!

How to redirect to the HTTPS version using .htaccess

Running our application code will be slower than using the server capabilities to perform the redirection for us!

To perform the 301 using .htaccess we just need to add the following lines to our file:

<IfModule mod_rewrite.c>
    RewriteEngine On

    # Check if the request is coming from post 80 instead of port 443
    RewriteCond %{SERVER_PORT} 80
    RewriteRule ^(.*)$ https://my-domain.com/$1 [R=301,L]
</IfModule>

Summary

We've seen how to perform a 301 redirect in several ways. It doesn't matter how you do it as long as you do it. Protect your users and your SEO :-)

Bibliography

 
Share this
Proudly part of