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:

  1. 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.

  2. Then make sure .htaccess and mod_rewrite module is working.

  3. 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

    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:

  1. It's faster.
  2. Your functions.php file remains cleaner & does what it's originally there for, i.e. Theme modifications.
  3. Changing the theme will not affect this.
  4. 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() {
    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 );

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.