pepebe
10/1/2012 - 8:07 PM

MODx Snippet: staticSubdomain - Redirect ststic files to several subdomains

MODx Snippet: staticSubdomain - Redirect ststic files to several subdomains

<?php
/*
    "staticSubdomain" - Create static domain path
				by info@pepebe.de
 
    According to this article (http://developer.yahoo.com/performance/rules.html#etags),
    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 www.example.org and split static components between static1.example.org and static2.example.org
    For more information check "Maximizing Parallel Downloads in the Carpool Lane" by Tenni Theurer and Patty Chi (http://yuiblog.com/blog/2007/04/11/performance-research-part-4/).
    "
   
    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 static0.example.com to static 3.example.com as subdomains and direct them to the same root as example.com
   
    [[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: http://paulirish.com/2010/the-protocol-relative-url/
    
    This will return something like this: http://static0.example.com
    
    Note: A filename will always result in the same subdomains. So there wont be any caching issues.
    
*/
    if(!function_exists('md5_hex_to_dec')){    
        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;