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]
yogaboyz88
  • 39
  • 8

1 Answers1

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;
    }
}
Vickel
  • 7,879
  • 6
  • 35
  • 56
  • 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 – yogaboyz88 Jul 27 '19 at 17:44
  • this might be an cache issue, try with another mobile browser or other phone – Vickel Jul 27 '19 at 17:55
  • I have tried with different devices and deleted the browser cache but still like that – yogaboyz88 Jul 28 '19 at 04:43
  • 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.com`and matches. Now it should match in the 1st place. please confirm. – Vickel Jul 28 '19 at 14:21
  • this works :) can you tell me, how to make this script run on all controllers?? – yogaboyz88 Aug 02 '19 at 02:32
  • *how to make this script run on all controllers*: read up on how to extend core classes, like here: https://stackoverflow.com/a/47304597/2275490 and here: https://stackoverflow.com/a/53548909/2275490. If you run into problems, ask a new question. Also read on: https://stackoverflow.com/help/accepted-answer – Vickel Aug 02 '19 at 14:52