4

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

  • Redirecting https to http you need to first have a valid ssl to make the initial handshake and then make the redirect. – Drupalizeme Nov 20 '17 at 18:57
  • 1
    W/ the function above I'm able to successfully redirect https to http. Downside is the user still has to pass through a scary browser prompt saying there is no valid ssl certificate. I'm fine with that for now - I'm just struggling with redirecting a www to non via preg_replace(). I need an 'or' operator in there somewhere saying 'https:// | https://www.' – Kyle Vassella Nov 20 '17 at 19:10
  • You can try this $url = $_SERVER['REQUEST_URI']; $redirect_url='' $not_allowed = array('https://wwww', 'https://'); foreach($not_allowed as $types) { if(strpos($url, $types) === 0) { $redirect_url = str_replace($types, 'http://', $url); } } – Drupalizeme Nov 20 '17 at 19:20
3

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
    </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:

  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.
  • Thanks for this. I've tried it, but for some reason changes to .htaccess won't take effect (I've tried your way and others). Wondering if I need to restart something to force it to work. – Kyle Vassella Nov 27 '17 at 15:43
  • First of all, if you don't install HTTPS (SSL) properly, then .htaccess rules for HTTPS may not work at all (I've written this in my answer already). Also, you must make sure .htaccess is actually working on your site, because if it does, restarting should not be necessary. – Fayaz Nov 28 '17 at 4:29
2

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.

  • Thanks so much for taking the time to do this. Unfortunately the www is not getting removed from the address bar in my case - I don't think it's redirecting. I did remove the extra 'w' typo from 'wwww' in your code, and also tried a version w/ if(strpos($url, $types) !==0) instead of your ===0 because I thought that may be the problem, but couldn't get it to work. I'll keep staring at it to see what I can change. If you have any ideas pls let me know. – Kyle Vassella Nov 20 '17 at 21:21
  • This is maybe due to the system .htaccess settings. I would try it in private window and look for hidden redirects. – Drupalizeme Nov 21 '17 at 6:03
  • Thx for coming back to this. I've tried doing this in .htaccess w/ yours and other methods, but can't get it to take effect - I think I may need to de-activate and re-activate my wordpress theme to get .htaccess changes to take effect, but I'm not ready to take that step (never done it). So I'll stick w/ PHP - still can't get it to work. Your way successfully redirects to https to http, but I still can't get it to remove the www subdomain. I checked in a private window and didn't see any hidden redirects in the Network tab (if thats how u check) - just the expected https -> http 301. – Kyle Vassella Nov 21 '17 at 22:17
  • I did notice after your if else statement you had the if shorthand: $redirect_url = !empty($redirect_url)?$redirect_url:$url; , but $url isn't defined globally here - its only defined in the if statement. Not sure if that's a reason or not - maybe $url is globally defined in PHP, or isn't needed anyways? – Kyle Vassella Nov 21 '17 at 22:24
  • @KyleVassella 1) The $url isn't something should be declared globally as it serves only the local scope for the if statement. It holds the $_SERVER['REQUEST_URI'] and should be taken in to account if the $redirect_url stay empty. 2) The .htaccess should work as is without the activation/deactivation of themes. But there is a big if this could change if there is a caching or something else interfering with the rules. I would try to push the rules at the top of the .htaccess. – Drupalizeme Nov 22 '17 at 7:57
0

Here, use this updated function to redirect a www site to non-www:

function bhww_ssl_template_redirect() {
    $redirect_url='';
    $url = $_SERVER['REQUEST_URI'];
    if ( shapeSpace_check_https() ) {
        if ( 0 === strpos( $url, 'http' ) ) {
            if(strpos($url, 'https://') === 0) {
                $redirect_url = str_replace('https://', 'http://', $url); 
            } 
        } 
        elseif ( TRUE == strpos( $url, 'www.') {
             $redirect_url = str_replace('www.', '', $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(); 
    }
}

Let me know if this helps.

  • Thanks for taking the time to do this. I didn't try it before I got my own version to work. I would have, but at the time couldn't risk possibly breaking the live site again. Your way may work, though off the top of my head I don't think it would redirect http://www.example.com to http://example.com since all the logic is inside of if (shapeSpace_check_https() ) , which I believe checks if https is being used. I could be wrong though. – Kyle Vassella Nov 27 '17 at 17:51
0

Thanks to everyone for your help. But the following code is what finally worked for me to 301 redirect https to http and www to non-www. I placed the following code block inside of functions.php:

//check if https being used regardless of certificate
function shapeSpace_check_https() { 
    if ((!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') || $_SERVER['SERVER_PORT'] == 443) {
        return true; 
    }
    return false;
}


for ($x=0; $x<1; $x++) {
    //if https:// && www.
    if ( shapeSpace_check_https() && substr($_SERVER['HTTP_HOST'], 0, 4) === 'www.'){
            header('HTTP/1.1 301 Moved Permanently');
            header('Location: http://' . substr($_SERVER['HTTP_HOST'], 4).$_SERVER['REQUEST_URI']);
            exit;
            break;
    //if only www.
    } elseif (substr($_SERVER['HTTP_HOST'], 0, 4) === 'www.') {
            header('HTTP/1.1 301 Moved Permanently');
            header('Location: http://' . substr($_SERVER['HTTP_HOST'], 4).$_SERVER['REQUEST_URI']);
            exit;
            break;
    //if only https://
    } elseif ( shapeSpace_check_https() ) {
            header('HTTP/1.1 301 Moved Permanently');
            header('Location: http://' . $_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']);
            exit;
            break;
    }
}

I don't think I need the break;'s, but I definitely need the exit;'s and I left the break;'s just in case. Please feel free to school me on why I may not need both. The code above results in the following redirects:

https://www.example.com to http://example.com

https://example.com to http://example.com

http://www.example.com to http://example.com

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.