**EDIT: I finally figured this out. Scroll down for my self-answered self-accepted answer (green check mark) **
I’m currently using functions.php
to redirect https
urls to http
for a site which currently has no SSL certificate:
function shapeSpace_check_https() {
if ((!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') || $_SERVER['SERVER_PORT'] == 443) {
return true;
}
return false;
}
function bhww_ssl_template_redirect() {
if ( shapeSpace_check_https() ) {
if ( 0 === strpos( $_SERVER['REQUEST_URI'], 'http' ) ) {
wp_redirect( preg_replace( '|^https://|', 'http://', $_SERVER['REQUEST_URI'] ), 301 );
exit();
} else {
wp_redirect( 'http://' . $_SERVER['HTTP_HOST'] .
$_SERVER['REQUEST_URI'], 301 );
exit();
}
}
}
add_action( 'template_redirect', 'bhww_ssl_template_redirect');
In this same function, I’d like to also redirect the www
subdomain to non-www. I’ve found a good function here, but need help implementing it into my current function. I’d like to avoid doing this in .htaccess
, but would welcome a solution there as well.
How to redirect HTTPS
to HTTP
and www
to non-www
URL with .htaccess
:
-
First make sure HTTPS
is working and valid. It’s easy (and free) to do with Let’s Encrypt these days.
Note: Although you are redirecting HTTPS
to HTTP
, I’d recommend doing it the opposite, i.e. HTTP
to HTTPS
. Better for Security, SEO & Browser compatibility – popular browsers are increasingly making it difficult for HTTP
sites.
-
Then make sure .htaccess
and mod_rewrite
module is working.
-
Then use the following CODE in the .htaccess
file of your web root directory (if you are already using some rules there, adjust them accordingly with these new rules):
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{HTTPS} =on [OR]
RewriteCond %{HTTP_HOST} !^example\.com$
RewriteRule ^(.*)$ "http://example.com/$1" [R=301,L]
# remaining htaccess mod_rewrite CODE for WordPress
</IfModule>
Note: Replace example.com
with your own domain name.
Why .htaccess
solution is better:
It’s better to do these sort of redirects with the web server. From your question, since your web server seems to be Apache
, it’s better to do with .htaccess
. Why:
- It’s faster.
- Your
functions.php
file remains cleaner & does what it’s originally there for, i.e. Theme modifications.
- Changing the theme will not affect this.
- For every redirect, the entire WordPress codebase doesn’t have to load twice – once before redirect & then after redirect.