WordPress Force Redirect HTTP to HTTPS using htaccess file

Once upon a time, I was installing a new WordPress on my new domain. After installing WordPress I have to install SSL and I have also installed SSL on my new domain.

But I have found an issue. When I was trying to visit my new website it still serves over HTTP. I was shocked. So I tried to visit my new website using HTTPS and it works. Then I realized that I have to force redirect HTTP to HTTPS using the .htaccess file. But I didn’t know how to do it.

The .htaccess file is a very important WordPress core file that is used for adding, modifying, and overriding server-level configurations, security, and performance parameters. So I started to search on Google about this issue and I have found a solution.

The solution was:

  1. I have to open the .htaccess file as editing mode
  2. Then I have to add the following code at the very first of the file.
RewriteEngine On
RewriteCond %{HTTPS} !=on
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301,NE]
Header always set Content-Security-Policy "upgrade-insecure-requests;"

After adding the above code the .htaccess file looks as follows:

RewriteEngine On
RewriteCond %{HTTPS} !=on
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301,NE]
Header always set Content-Security-Policy "upgrade-insecure-requests;"

# BEGIN WordPress
# The directives (lines) between "BEGIN WordPress" and "END WordPress" are
# dynamically generated, and should only be modified via WordPress filters.
# Any changes to the directives between these markers will be overwritten.
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>

# END WordPress

That’s how I solved my issue force redirect HTTP to HTTPS using the .htaccess file.

Leave a Comment