2

I want to direct mydomain.com to m.mydomain.com if the user opens the website via mobile. I use mobiledetect.net and I have installed it using a composer. when I try to open a website via my mobile I get an error notification "ERR_TOO_MANY_REDIRECTS".

This my controller :

class Welcome extends CI_Controller {

    public function __construct()
    {
        parent::__construct();
        $this->load->helper('url');
    }

    public function index()
    {
        $detect = new Mobile_Detect;
        if($detect->isMobile()) {
            header("location: http://m.mydomain.com");
            exit;
        }
    }
}

how can I fix this error?

I only use the default htaccess from the CI documentation

HTACCESS

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php/$1 [L]
2
  • please show your .htaccess or windows equivalent Commented Jul 27, 2019 at 14:59
  • I only use the default htaccess from the CI documentation Commented Jul 27, 2019 at 16:04

1 Answer 1

0

you need to exclude detection of mobile, when you are using the mobile site. You can achieve this like this:

public function index()
{
    $host='http://'.$_SERVER["HTTP_HOST"];
    $detect = new Mobile_Detect;
    if($detect->isMobile() && $host!='http://m.mydomain.com') {
        header("location: http://m.mydomain.com");
        exit;
    }
}
Sign up to request clarification or add additional context in comments.

6 Comments

this works. but before going directly to m.mydomain.com, the error message still appears about a few seconds. not directly to m.mydomain.com
this might be an cache issue, try with another mobile browser or other phone
I have tried with different devices and deleted the browser cache but still like that
I've added 'http://'to build the $host variable. Now it should match at the first try. before it was looking to match m.mydomain.com, which it didn't (hence the error) then redirects to http://m.mydomain.comand matches. Now it should match in the 1st place. please confirm.
this works :) can you tell me, how to make this script run on all controllers??
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.