10/1/2012 - 8:07 PM

MODx Snippet: staticSubdomain - Redirect ststic files to several subdomains

MODx Snippet: staticSubdomain - Redirect ststic files to several subdomains

    "staticSubdomain" - Create static domain path
    According to this article (,
    you can enhance the perceived performance of a webpage by redirecting static files (images, css, js) to several subdmains.
    Quote: "
    Splitting components allows you to maximize parallel downloads.
    Make sure you're using not more than 2-4 domains because of the DNS lookup penalty.
    For example, you can host your HTML and dynamic content on and split static components between and
    For more information check "Maximizing Parallel Downloads in the Carpool Lane" by Tenni Theurer and Patty Chi (
    With this snippet you can append one of four static subdomains to any filepath.

    Note: You have to set those subdomains in cpanel BEFORE you redirect your files or brew up some wildcard htaccess rules.
    Example: Create to static as subdomains and direct them to the same root as
    [[staticSubdomain? &filename=`[[+image]]` &subdomain=`static` &protocol=`http:` ]]
    &filename=``    Any valid filename including extension
    &subdomain=``   A subdomain. "static" for example.
    &protocoll=``   A protocol "http:" or "https:" for example. Hint: DON'T forget the colon!
                    If no protocol is given, the snippet will assume a protocol relative url: "//".
                    If you want to learn about this technique, Read this:
    This will return something like this:
    Note: A filename will always result in the same subdomains. So there wont be any caching issues.
        function md5_hex_to_dec($hex_str)
            $arr = str_split($hex_str, 4);
            foreach ($arr as $grp) {
            $dec[] = str_pad(hexdec($grp), 5, '0', STR_PAD_LEFT);
            return implode('', $dec);

    $hash = hash(md5, $filename);
    $hexdec = md5_hex_to_dec($hash);

    $decbin = decbin(substr($hexdec,0,9));
    $strlen = strlen($decbin); 
    // We only need the last two bits
    $characters = 2; 
    $start = $strlen - $characters; 
    $substr = substr($decbin , $start ,$characters);

    $domain = $_SERVER['HTTP_HOST'];
    $staticSubdomain = $protocol."//".$subdomain.bindec($substr).".".$domain;

return $staticSubdomain;