www vs no-www and cookies

May 13th, 2008. Tagged: performance, php

One of Yahoo's performance rules says: Use cookie-free domains for static components. This is good because the server has no use for cookie information when serving a JPEG or another static component, so all this cookie information creates network traffic for no reason.

One of the implications of following the rule is related to the whole www vs no-www question. Basically you should always use www if you're planning to use any other sub-domains and you want them cookie-free. This is because you have no way to set a cookie only to the top-level domain. So for example you cannot write a cookie only to phpied.com. If you load component from img.phpied.com, the cookie from phpied.com will be sent again. In Firefox this doesn't seem to be the case, but in IE it is.

Here are two test scripts that demonstrate the behavior:

Load both of these pages and then reload them to see what cookies are sent. They both try to set cookies in all possible ways:

  1. omitting the domain name
  2. .domain.com
  3. domain.com
  4. www.domain.com

Here's the source code of the files:

nowww.php [test]

<?php
setcookie('no0', 'no www, no domain');
setcookie('no1', 'no www, .phpied.com', 0, '/', '.phpied.com');
setcookie('no2', 'no www, phpied.com', 0, '/', 'phpied.com');
setcookie('no3', 'no www, www.phpied.com', 0, '/', 'www.phpied.com');
 
echo '<pre>';
print_r($_COOKIE);
?>

yeswww.php [test]

<?php
setcookie('yes0', 'yes www, no domain');
setcookie('yes1', 'yes www, .phpied.com',    0, '/', '.phpied.com');
setcookie('yes2', 'yes www, phpied.com',     0, '/', 'phpied.com');
setcookie('yes3', 'yes www, www.phpied.com', 0, '/', 'www.phpied.com');
 
echo '<pre>';
print_r($_COOKIE);
?>

Loading the two pages twice shows how in IE, no0, no1, and no2 are all visible when using www as well as when not using it. In Firefox it's almost the same, only that no0 is not visible when using www.

As a take-home:

  • use www
  • write cookies to the appropriate domain level (e.g. don't write to *.domain.com)

Tell your friends about this post on Facebook and Twitter

Sorry, comments disabled and hidden due to excessive spam.

Meanwhile, hit me up on twitter @stoyanstefanov