We launched new forums in March 2019—join us there. In a hurry for help with your website? Get Help Now!
    • 18654
    • 191 Posts
    Any idea why modx->sendRedirect might be causing a server error (500) when native php header works? This code executes in the onHandleRequest event.

    Not working using modx->sendRedirect:

    // redirect www to non www
    if(preg_match('/^www/', $_SERVER['SERVER_NAME'])) {
         $url = trim($modx->context->config['base_url'], '/') . $_SERVER['REQUEST_URI'];
         $modx->sendRedirect($url, array('responseCode' => '301'));
    }
    


    Working using php header

    // redirect www to non www
    if(preg_match('/^www/', $_SERVER['SERVER_NAME'])) {
    	$url = trim($modx->context->config['base_url'], '/') . $_SERVER['REQUEST_URI'];
    	header("Location: $url", TRUE, 301);
    }
    


    Also, $modx->sendRedirect seems to work fine on my local environment (wamp 2.0 / W7) with the response code but not on production (bluehost / linux)
    Modx version is: 2.1.0-pl (traditional)

    Additionally, $modx->sendRedirect works fine on production without the responseCode option.
      God does not save those who are only imaginary sinners. Be a sinner, and let your sins be strong, but let your trust in Christ be stronger, and rejoice in Christ who is the victor over sin, death, and the world.
      • 22303 MODX Staff
      • 10,725 Posts
      First, the responseCode parameter needs to be the actual full HTTP response code, e.g.

      $modx->sendRedirect($url, array('responseCode' => 'HTTP/1.1 301 Moved Permanently'));


      Second, you should always use an absolute URL (including scheme and host_name) as the first parameter, e.g.

      $url = trim($modx->getOption('site_url'), '/') . $_SERVER['REQUEST_URI'];

      or
      $url = $modx->getOption('url_scheme') . $modx->getOption('http_host') . $_SERVER['REQUEST_URI'];
        • 18654
        • 191 Posts
        That worked great - thanks!
          God does not save those who are only imaginary sinners. Be a sinner, and let your sins be strong, but let your trust in Christ be stronger, and rejoice in Christ who is the victor over sin, death, and the world.