Home > DevOps > Redirect HTTP to HTTPS in htaccess file

Redirect HTTP to HTTPS in htaccess file

All web browsers default their initial connection to a HTTP server over an insecure connection. You can always have a site served over port 80 so HTTP will always be good to connect on, but you might not have an SSL certificate on a website making it available on port 443 so browsers default to the insecure connection as it will always be available.

*** Please see the site-wide Disclaimer which can be found on the Legal page ***

The following snippet is designed to be used if you want to redirect all connections to a website to an HTTPS connection. So this content should be put into the .htaccess file in the folder where the site root is located.

The mod_rewrite module needs to be enabled for this to work. The following lines are necessary and need to be between then opening and closing section for the RewriteEngine.

RewriteCond %{HTTPS} !=on
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

The opening segment will look like this:

<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /

And the closing tag is:

</IfModule>

You might have content already in here. For instance, if your hosting a WordPress site, your whole .htaccess file will look like:

<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /

# BEGIN WordPress
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>

To just add redirection to the base .htaccess file you would end up with:

<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /

RewriteCond %{HTTPS} !=on
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
</IfModule>

If your hosting a WordPress site and want to redirect all requests to HTTPS your complete .htaccess file would look like this.

<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /

RewriteCond %{HTTPS} !=on
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]


# BEGIN WordPress
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>

If you have any questions or would like to assist with setting up your hosting account at whatever provider you use, contact me and we’ll see what we can work out.