WordPress – How to serve static content from a cookieless domain

If you’re serious about optimising a WordPress website for speed, then you need to setup your website to serve the static content, such as images and css files, from a cookieless domain. This will speed up your page loads by reducing unnecessary traffic and distributing the traffic across more two addresses instead of one, working around the limit that browsers place on how many simultaneous requests can be made on each address.

As described by Yahoo!, when the browser requests a static image and sends cookies with the request, the server ignores the cookies. These cookies are unnecessary network traffic.

The steps below detail how to configure your WordPress install to serve static content from a cookieless domain.

Please note:

  • This is by no means a simple process. You will need a good understanding of how website hosting works, including logging into your hosting account, configuring domain names, configuring the WordPress wp-config.php file and applying bulk changes to the database using phpMyAdmin.
  • This can only work if you run your website from a www. address, e.g. www.itsupportguides.com — this allows you to separate the ‘cookie’ domain (www) and the cookieless domain (static).
  • This process, specifically step 3, will involve bulk changes to your content using database tools. I highly suggest you create a backup of your WordPress database before continuing. Using phpMyAdmin this can be done using the ‘export’ option.
  • Depending on the websites hosting environment it can take up to 24 hours for the new static sub-domain to start working. Typically it takes 5-15 minutes, but propagation of DNS changes can take up to 24 hours.
  • CloudFlare users – you cannot satisfy the ‘cookieless domain’ criteria when running the website through CloudFlare – this is due to CloudFlare adding a “security cookie” to all content being served through their website. See CloudFlare website. This is because CloudFlare assign a cookie to the domain name (e.g. .itsupportguides.com) instead of the website address (e.g. www.itsupportguides.com)
  • Google Analytics users – you will need to modify your Analytics code (also upgrading it to the latest version, if you haven’t already) and check that your Analytics configuration is setup correctly.
  • HTTPS/HTTP – this is the same process regardless of if your website is served over HTTP or HTTPS.

Step 1: Create a subdomain using cPanel for the static content

The steps below are for cPanel managed websites. The process may be different depending on the hosting environment for your website.

  1.  Log into the cPanel for your website. The address is usually www.website.com/cpanel, and the username and password would have been provided by your host when you first joined.
  2. Under ‘Domains‘, click on the icon for ‘Subdomains’
  3. WordPress-StaticContent1
  4. In the ‘Create a subdomain’ box enter static in the ‘Subdomains field and in the ‘Document Root’ field enter the path to the wp-content folder, for example /public_html/wp-content
  5. WordPress-StaticContent2
  6. Click on the ‘Create’ button and wait for confirmation that the subdomain has been created
  7. You will now be able to open static.domainname.com and see a blank page
  8. IMPORTANT: Test to make sure that your static address is loading – e.g. http://static.domainname.com (or https if you use it). DO NOT PROGRESS UNTIL THIS LOADS — you will see a blank page when it is working correctly.

Note: it takes time for new subdomains to be available. Typically it takes about 10 minutes, but can take up to 24 hours depending on how you access the Internet. If you’re having problems accessing the subdomain, try from another Internet connection or using an online tool such as Pingdom Tools.

Step 2: Configure WordPress

  1.  Using your preferred method, for example FTP or through the cPanel, navigate to the root directory of your WordPress installation and edit wp-config.php
  2. Add the following lines to the top of the file, below the <?php
  3. Replace domainname with the domain name for your website
  4. define("WP_CONTENT_URL", "http://static.domainname.com");
    define("COOKIE_DOMAIN", "www.domainname.com");
    define("WP_PLUGIN_URL", "http://static.domainname.com/plugins");
  5. WordPress-StaticContent3
  6. Save the changes to wp-config.php.

Step 3: Update existing post content

Now WordPress is configured to serve the static content in wp-content through the static subdomain.

New images added to posts will now automatically use the static subdomain, however existing image paths need to be updated to use the static domain.

  1.  Log into the cPanel again
  2. Under ‘Databases’, click on the icon for ‘phpMyAdmin’
  3. WordPress-StaticContent4
  4. Expand the database for the WordPress installation and click on the posts table
  5. WordPress-StaticContent5
  6. Click on the ‘Inline’ link, then in the text box enter the following command
  7. Replace domainname with the domain name for your website
  8. UPDATE wp_posts SET post_content = REPLACE(post_content,
     'http://www.domainname.com/wp-content/uploads/','http://static.domainname.com/uploads/')
  9. WordPress-StaticContent6
  10. Click ‘Go’ to apply the changes
  11. From the WordPress admin, check a few existing posts to make sure images are loading from static.domainname.com

And you’re done – one step closer to WordPress speed perfection!

ADDITIONAL STEP: Google Analytics users

If your website uses Google Analytics you will need to modify the Google Analytics code used on your website to specify the cookie domain and check that the settings on the Google Analytics account has the same address.

Modifying the Analytics code

You will need to change the property in the Analytics code from ‘auto’ to the www. address for your website. e.g. for www.itsupportguides it would be

<script>
  (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
  (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
  m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
  })(window,document,'script','//www.google-analytics.com/analytics.js','ga');

  ga('create', 'UA-XXXXXXX-1', 'www.itsupportguides.com');
  ga('send', 'pageview');
  ga('set', 'displayFeaturesTask', null);

</script>

Configure the Analytics account

  1. Open https://analytics.google.com
  2. Open the the website then go to the ‘Admin’ menu
  3. under ‘Property’ -> ‘Property Settings’ make sure both the ‘Property Name’ and ‘Default URL’ has the www. address for your website
  4. wordpress-staticcontent7
  5. For good measure, make the same change under ‘View’ -> ‘View Settings’ for ‘Website’s URL’
  6. wordpress-staticcontent8

OPTIONAL: Additional step if your theme uses font awesome icons

If your theme uses font awesome for icons, such as a ‘home’ or ‘search’ icon – you will need to add the following to your .htaccess file to allow the icons to continue to work.

Replace the domain name with the domain name for your website.

## EXPIRES CACHING ##

# ------------------------------------------------------------------------------
# | CORS-enabled images |
# ------------------------------------------------------------------------------
    
        <FilesMatch "\.(cur|gif|ico|jpe?g|png|svgz?|webp)$">
            SetEnvIf Origin ":" IS_CORS
            Header set Access-Control-Allow-Origin "http://www.domainname.com" env=IS_CORS
        </FilesMatch>
    
# ------------------------------------------------------------------------------
# | Web fonts access |
# ------------------------------------------------------------------------------

# Allow access from all domains for web fonts

    <FilesMatch "\.(eot|otf|ttc|ttf|woff)$">
        Header set Access-Control-Allow-Origin "http://www.domainname.com"
    </FilesMatch>

Help! My website still isn’t passing the cookieless domain test

This is where things can get complicated – you now need to use a browser debugging tool to load a resource (e.g. an image or a html page) from the static domain and check through each of the cookies that are coming through with the resource.

For each cookie you will need to fix why they’re coming into the static domain.

For this I prefer to use Firefox and Firebug.

Using Firefox and Firebug – I’ve loaded the resource, opened Firebug then the Cookies tab.

From here you can see a list of the cookies that loaded on the static domain (note – I had to completely clear my browsers cache, even when using ‘private browsing’ to make this 100% accurate).

This example shows the CloudFlare security cookie – which can not be removed without disconnecting the website from CloudFlare.

wordpress-staticcontent9

 

Related Articles

46 comments on “WordPress – How to serve static content from a cookieless domain

  1. after I make the changes to the wp-config file save and reupload the new wp-config to the ftp my site stops working and only displays a white screen, does anyone know why this is happening or a possible fix? I am willing to pay someone via paypal to help me get this working. thanks

  2. after I make the changes to the wp-config file save and reupload the new wp-config to the ftp my site stops working and only displays a white screen, does anyone know why this is happening or a possible fix? I am willing to pay someone via paypal to help me get this working.

    1. Alex,

      If you know your database name, username and password, it is probably best to download WP 4.7 to your pc, then copy the db info in the new wp-config.php file from and upload it to replace the corrupted file.

      What is it that you were trying to do?

  3. I can’t login to /wp-admin because “ERROR: Cookies are blocked or not supported by your browser. You must enable cookies to use WordPress.” I’m kinda a wordpress scrub, any ideas?

    1. Hi Tashar – no, it is the same process for HTTPS or HTTP traffic websites. I have however learned a few new conditions to making this work. Your main website MUST be served using the www. address. If you’re using Google Analytics you need to specify the www address in the settings (see updated instructions above) and you cannot use ClareFlare. If it still doesnt work you can use a browser debug tool to load the static domain and check which cookies are coming through – you’ll then need to work on each individual cookie. Does this help?

    2. Actually i will tell a brief of my situation here.I have a https. And i have created a subdomain whose document root is wp-content. But when i change the wp-content url in wp-config file all the content somes from right path but an https is added to it. WHen i visit the subdomain url it takes http on it. The page source of the website shows the files (ie css and js ) taken as https. when i remove the ‘s’ from https in the file link the file is called properly in the browser. What does this mean why is the subdomain directed to https?

  4. I’ve followed the process down to the t. Only problem I get is pingdom still shows that images aren’t being served from static domain. Below is the url: http://wordpress.csaerotherm.com

    and here is my wp-conifg.php

    define(‘COOKIE_DOMAIN’, ‘wordpress.csaerotherm.com’); // don’t omit the leading ‘.’
    define(“WP_CONTENT_URL”, “http://static.csaerotherm.com”);
    #define(“COOKIE_DOMAIN”, “http://wordpress.csaerotherm.com”);
    define(“WP_PLUGIN_URL”, “http://static.csaerotherm.com/plugins”);
    define(‘ADMIN_COOKIE_PATH’, ‘/wp-admin/’);
    //define(‘COOKIE_DOMAIN’, ”);
    define(‘COOKIEPATH’, ”);
    define(‘SITECOOKIEPATH’, ”);
    #define(“DOMAIN_CURRENT_SITE”, “http://wordpress.csaerotherm.com”);
    #define(‘WP_CACHE’, true); //Added by WP-Cache Manager
    define(‘ENABLE_CACHE’, true); // enable the cache
    define(‘CACHE_EXPIRATION_TIME’, 3600); // in seconds

    Where have I gone wrong?? any help please??

    Thanks

    1. Hey,

      It looks like your WordPress config is correct, and content is being served from the static domain correctly – but the cloudflare service is being used – which adds a cookie.

      I hit this problem as well and decided the benefit of cloudflare was worth the potential SEO rank loss.

      Here’s what CloudFlare have to say about it: https://support.cloudflare.com/hc/en-us/articles/200169816-Can-I-serve-a-cookieless-domain-or-subdomain-through-CloudFlare-

      When it comes to SEO, I would worry less about what the tools say and more about making sure the website loads super fast, keep image sizes down (page load size/time), and pack the content with the right keywords people will be searching for. But that’s just my two-cents.

      Perhaps you can try excluding static.* using the page rules in CloudFlare? I think I tried that and it didnt work.

    1. Hey,

      It sounds like the plugin isnt using the correct methods for calling URL’s. Files/plugins/themes still live in the same spot on your server – what changes is the path you can use to load the resources.

      What’s the name of the plugin? Is it on the WordPress plugin directory? I’ll check it out and see what’s going on.

    2. Thank you for your reply!

      I finally figured out what I did wrong. When creating the subdomain you must set the document root the same as the wordpress installation wp-content directory.

      In the step 1.4 you say “for example: —” so I wrote “static” instead of “public_html/wp-content”. And that’s what was wrong.

  5. Hi,
    I use iTheme Security on my WP to hide backend (wp-login) area.
    I have this part of code on .htaccess to do that:
    # Enable the hide backend feature – Security > Settings > Hide Login Area > Hide Backend
    RewriteRule ^(/)?modir/?$ /wp-login.php [QSA,L]
    RewriteRule ^(/)?wp-register-php/?$ /wplogin?action=register [QSA,L]

    Everything worked normally but after following your guide I’m not able to login into my WP admin area anymore.
    could you please help me to figure it out and resolve the problem?

    1. I figured out by myself, there was W3total cache problem!

      In this line ‘pgcache.check.domain’ => true, of w3tc-config/master.php file, I change the “false” to “true” and resolved my problem! But I’m not sure that was right way to do or not, anyway it’s work 🙂

    1. Hey Tom. I’ve seen people say it can take up to 24 hours for a sub domain to be available, but really it depends the network you use to access the internet. For example, typically new sub domain is up and running in 10 minutes, but when Im accessing the Internet through a corporate network it tends to take up to an hour. If you’re not sure if it’s working or not you can run a address through a online testing tool, like https://tools.pingdom.com/
      If it works for them and not for you – try restarting your modem to see if that helps at all. You could also try pinging the subdomain in the windows command prompt – if it returns an IP address it should be working for serving content.

  6. Hi i have tryed every here and the layout messes up and images disappear as if it does not pull from location done an inspect element on website and it shows that the images are trying to come from static.domain.com (domain.com is not my real domain using as example).

Leave a Reply

Your email address will not be published.