Wordpress - PHP - redirect https to http and www to non-www
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
toHTTP
, I'd recommend doing it the opposite, i.e.HTTP
toHTTPS
. Better for Security, SEO & Browser compatibility - popular browsers are increasingly making it difficult forHTTP
sites.Then make sure
.htaccess
andmod_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.
Taken from your code I would refactor it like this:
function bhww_ssl_template_redirect() {
$redirect_url='';
if ( shapeSpace_check_https() ) {
if ( 0 === strpos( $_SERVER['REQUEST_URI'], 'http' ) ) {
$url = $_SERVER['REQUEST_URI'];
$not_allowed = array('https://www', 'https://');
foreach($not_allowed as $types) {
if(strpos($url, $types) === 0) {
$redirect_url = str_replace($types, 'http://', $url);
}
}
} else {
$redirect_url ='http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
}
$redirect_url = !empty($redirect_url)?$redirect_url:$url;
wp_redirect($redirect_url, 301 );
exit();
}
}
Add it the .htaccess
rules for the redirect www-> non - www
RewriteEngine On
RewriteCond %{HTTP_HOST} ^www.yourdomain.com [NC]
RewriteRule ^(.*)$ http://yourdomain.com/$1 [L,R=301]
Redirecting https->http
RewriteEngine On
RewriteCond %{HTTPS} on
RewriteRule (.*) http://%{HTTP_HOST}%{REQUEST_URI}
But again for this to work you need to have a valid SSL or the "Terror screen" will be shown to users.