What Are HTTP Cookies?
Each subsequent time the user browses the same site, their browser sends the cookie to the website’s server thus providing it with the information that was set in the last request. There are three main uses for cookies including:
- Session management
There are also various types of cookies available and can each be used in different scenarios.
Why Use Cookie-Free Domains?
Although cookies are very useful in some cases, in other cases – such as the delivery of static content, they can hinder performance. When a browser makes a request for a static asset such as an image or CSS file, there is no need for it to also send a cookie to the server. This only creates additional network traffic and since the files are static (they do not change) the server has no use for the added cookie.
When you use cookie-free domains you are able to separate the content that doesn’t require cookies from the content that does. This helps improve your site’s performance by eliminating unneeded network traffic.
How To Use Cookie-Free Domains WordPress
If you set your cookies on a top-level domain (e.g. yourwebsite.com) all of your sub-domains (e.g. static.yourwebsite.com) will also include the cookies that are set. Therefore, in this case, it is required that you use a separate domain name to deliver your static content if you want to use cookie-free domains. However, if you set your cookies on a www subdomain such as www.yourwebsite.com, you can create another subdomain (e.g. static.yourwebsite.com) to host all of your static files which will no longer result in any cookies being sent.
The following steps outline how to** use cookie-free domains in WordPress**:
- Create a subdomain such as static.yourwebsite.com which is where you will deliver all your static files from.
- Point your new subdomain to the /wp-content directory of your WordPress installation. For cPanel users, you will need to update the document root field from public_html/static to public_html/wp-content like the screenshot below.
- Edit your wp-config.php file to reflect the following:
define("WP_CONTENT_URL", "http://static.yourwebsite.com"); define("COOKIE_DOMAIN", "www.yourwebsite.com");
- Run the following command in your SQL database, this will ensure all post URLs are directed to the new subdomain:
UPDATE wp_posts SET post_content = REPLACE(post_content,'www.yourwebsite.com/wp-content/','static.yourwebsite.com/')
Now that your cookie domain and static content subdomain are set, you can begin delivering static content without the server setting an unnecessary cookie for static assets.