简体   繁体   中英

Redirect users from other websites based on browser language

I want to do this:

if (user from other website, like google, or input our website URL directly in the browser)
{
//redirect according to browser languge
        if (!preg_match('/en-US/', $_SERVER['HTTP_USER_AGENT']))
        {
        wp_redirect("http://cn.gearor.com");
    }
}

I don't know how to write the first if statement, I don't know how to get the from URL and how to check it's my website or other websites. If it's my website, do nothing, if it's not my website, check if the browser is English, if not, redirect to http://cn.gearor.com

$_SERVER['HTTP_REFERER'] is the full URL that led to the page that checks it. It's not guaranteed to be set, though it's the only way to know what you're looking for.

Also, you may want to check $_SERVER['HTTP_ACCEPT_LANGUAGE'] instead of $_SERVER['HTTP_USER_AGENT'] for the language of the user.

Here is the full reference to the $_SERVER superglobal array. You should check the keys, especially those starting with HTTP_ .

You want something like:

if (!preg_match('%your_domain.tld%i', $_SERVER['HTTP_REFERER']))
{
    if (!preg_match('/en-us/i', $_SERVER['HTTP_ACCEPT_LANGUAGE']))
        // .. do your stuff here.
}

I changed your language check to use HTTP_ACCEPT_LANGUAGE, and to also not be case sensitive (Opera uses en-US where Firefox and IE use en-us in my tests).

You could also consider using /^en-us/i if you are checking for the DEFAULT language. The language strings can contain multiple languages, comma delimited.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM