I have tirelessly tried to force HTTPS to my entire WordPress website after activating my free SSL certificate I received from 1and1 hosting so that all past HTTP links are redirected to HTTPS. I want to force HTTPS by modifying only the .htaccess file in the root of my web folder. I have tried multiple examples I have found on the web including:
http://www.wpbeginner.com/wp-tutorials/how-to-add-ssl-and-https-in-wordpress/
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{SERVER_PORT} 80
RewriteRule ^(.*)$ https://www.yoursite.com/$1 [R,L]
</IfModule>
https://www.1and1.com/digitalguide/hosting/technical-matters/the-ten-best-htaccess-tricks/
<IfModule mod_rewrite.c>
# activate HTTPS
RewriteEngine On
RewirteCond %{Server_Port} !=443
RewriteRule ^(.*)$ http://yourdomain.tld/$1 [R=301, L]
</IfModule>
After trying all these methods of modifying the .htaccess file, none of them worked. I finally came across this Stack Overflow question and put the PHP block of code in the functions.php file in my current theme folder. Here is the code:
if (!isset($_SERVER['HTTPS']) || $_SERVER['HTTPS'] !== 'on') {
if(!headers_sent()) {
header("Status: 301 Moved Permanently");
header(sprintf(
'Location: https://%s%s',
$_SERVER['HTTP_HOST'],
$_SERVER['REQUEST_URI']
));
exit();
}
}
This PHP code accomplished my goal of forcing all links to HTTPS. However, I desire to keep my code clean and leave it all in the .htaccess file for better organization and so I don't have to remember to add the PHP code to the functions.php file every time I change the theme of my WordPress website.
Could anyone please explain how to accomplish forcing HTTPS by ONLY modifying the .htaccess file or explain where I may have gone wrong?
The only active block of code in my .htaccess file is this:
# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>
# END WordPress
AddHandler x-mapp-php5.5 .php
And I already changed my WordPress settings of "WordPress Address (URL)" and "Site Address (URL)" to "https://example.com/".