Force HTTP to HTTPS Using 301 Permanently Redirect in .htaccess file

On  

Sometimes installing plugins for every type of purpose you want is wrong. Some small tasks could be done by just a very small tweak.

When you have just enabled SSL for your website, some of the URLs to your previous content might be still in HTTP. We can force them to redirect to HTTPs.

To do so, put the following codes in between and of your .htaccess file in the root of your website:

RewriteCond %{HTTPS} off
RewriteCond %{HTTP_HOST} ^(?:www\.)?(.*)$ [NC]
RewriteRule (.*) https://%1%{REQUEST_URI} [L,R=301]

If you are using WordPress, the .htaccess file will look like this:

# BEGIN WordPress

RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]

RewriteCond %{HTTPS} off
RewriteCond %{HTTP_HOST} ^(?:www\.)?(.*)$ [NC]
RewriteRule (.*) https://%1%{REQUEST_URI} [L,R=301]

# END WordPress

And if we want to always redirect from www to non-www, the .htaccess code becomes:

# BEGIN WordPress

RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]

RewriteCond %{HTTPS} on 
RewriteCond %{HTTP_HOST} ^www\.(.*)$ [NC]
RewriteRule ^(.*)$ https://%1/$1 [R=301,L]

About Author:

I am a WordPress lover. I make my living by using WordPress.

Leave A Comment

Your email address will not be published. Required fields are marked *