We launched new forums in March 2019—join us there. In a hurry for help with your website? Get Help Now!
    • 29635
    • 361 Posts
    Ok, so the elegant 3 line .htaccess mod of JeremyL SEO Strict URLs works much better, but if anybody needs the same functionality in a snippet, I just wrote one.

    What it’ll do:
    Take any visitor’s URL request that does not contain a www and redirect to the www page.

    NOTE:
    The above mentioned .htaccess hack is better, if you can use it. I’m posting this on the chance that somebody can’t use that trick for whatever reason. Maybe that’s nobody wink

    <?php
    // WWWRedirect
    // Redirect to the www address if www isn't included in the URL
    
    // Determine the host
    $host = $_SERVER['HTTP_HOST'];
    // Determine if it's http or https
    $http = ($_SERVER['HTTPS'] == 'on' ) ? 'https://' : 'http://';
    // Check if the host starts with "www." or not
    $www = preg_match("/^www\./", $host);
    // Get the filename
    $self = $modx->makeURL($modx->documentObject['id']);
    
    if ( $www == '0' ) {
        $host = $http . 'www.' . $host . $self;
        $modx->sendRedirect($host);
    } else {
        return '';
    }
    ?>
      Need MODx Ecommerce? Try FoxyCart!
      • 28042 ☆ A M B ☆
      • 24,524 Posts
      Wouldn’t this be better as a plugin, set to run as soon as possible? Then it would avoid all that snippet parsing before redirecting.
        Studying MODX in the desert - http://sottwell.com
        Tips and Tricks from the MODX Forums and Slack Channels - http://modxcookbook.com
        Join the Slack Community - http://modx.org
        • 29635
        • 361 Posts
        Yes, it most certainly would wink

        If anybody has any interest in a plugin I’ll switch it up, but I think the .htaccess is better for most purposes.
          Need MODx Ecommerce? Try FoxyCart!