Php redirect to url without www if possible

2019-09-18 06:18发布

问题:

I have small proxy when i need to get same URLS from same website, but in some websites URL could be with WWW and without, i was going to cut WWW and redirect to http:// only. But some sites redirect to http://www anyway and im getting infinite redirect.

Thats why i have tried to redirect without WWW and if it still with WWW (after redirect) leave it with http://www.

I was trying to avoid this by $_SESSION where i can store if it was redirected or not, and execute redirect if not.

But it still infinite redirecting me on website with www im searching the solution several days. - and still nothing. Passing if redirected in $_GET paramenter is not exit, because url should be clean.

Also im storing domain in session to know that user change website and need to check for www.

if(session_id() == '') {
    session_start();
}
if(strpos($_url, "www")!==false) {
    if(!isset($_SESSION['redirected'])) {
        $_SESSION['redirected']=get_domain($_url);
        $url = preg_replace('#^(http(s)?://)?w{3}\.(\w+\.\w+)#', '$1$3', $url);
        header("Location: ".$script_url . '?' . $config.'='.$url);      
        exit(0);
    }
    elseif($_SESSION['redirected']!=get_domain($_url)) {
        $url = preg_replace('#^(http(s)?://)?w{3}\.(\w+\.\w+)#', '$1$3', $url);
        header("Location: ".$script_url . '?' . $config.'='.$url);      
        exit(0);
    }
}
session_destroy();