最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

functions - PHP - redirect https to http and www to non-www

programmeradmin0浏览0评论

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

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

Share Improve this question edited Jun 15, 2020 at 8:21 CommunityBot 1 asked Nov 20, 2017 at 18:04 Kyle VassellaKyle Vassella 1631 gold badge1 silver badge8 bronze badges 3
  • Redirecting https to http you need to first have a valid ssl to make the initial handshake and then make the redirect. – Drupalizeme Commented Nov 20, 2017 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 Commented Nov 20, 2017 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 Commented Nov 20, 2017 at 19:20
Add a comment  | 

4 Answers 4

Reset to default 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\$
        RewriteRule ^(.*)$          "http://example/$1" [R=301,L]
    
        # remaining htaccess mod_rewrite CODE for WordPress
    </IfModule>
    

    Note: Replace example 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() {
    $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 [NC]
RewriteRule ^(.*)$ http://yourdomain/$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 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 to http://example

https://example to http://example

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

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.

发布评论

评论列表(0)

  1. 暂无评论