Use a cookie free domain to serve static content with Nginx
Written by Guillermo Garron
Date: 2011-08-11 11:20:00 00:00
Part of the Best Practices for Speeding Up Your Web Site is Use Cookie-free Domains for Components.
And what does this means?
It means that you should serve your static content, from a domain where no cookies have been sent to the browser.
How can you achieve this?
You best bet is to create a new domain, it can be a sub-domain, something like: static.yourdomain.com or a complete new domain, like static-yourdomain.com, and there you can create a subdomain to use, let’s say images.static-yourdomain.com
Now you can use Nginx to serve your static content from this new domain.
We’ll first configure Nginx to serve only the static content form here, and then we’ll see how to call your css files and images from this domain.
Configure Nginx to serve images from a cookie-free domain
What I’ve done here, is to point the new domain in the DNS to the same server that the original domain is pointed to:
Something like this:
yourdomain.com A 12.13.14.15 static.static-yourdomain.com A 12.13.14.15
Now in the configuration of the server 12.13.14.15 we need to edit the ngix.conf
file.
server { listen ip:80; server_name yourserver.com; root /srv/http/nginx/yourserver.com; access_log logs/yourserver.com.access.log; location / { index index.html; charset utf-8; } } } server { listen ip:80; server_name static.static-yourserver.com; root /srv/http/nginx/yourserver.com; location / { if ($request_filename ~ "\.(jpg|css|gif|png|swf|ico|mp3)$") { break; } return 404; } }
In the first server section, you are defining your real domain, where all your pages are, in the second section, you are defining the static content server, note that you are pointing both to the same folder, so if you do nothing, your content will be available from two different urls, http://yourdomain.com and http://static.static-yourdomain.com, and Google may penalize you for duplicated content.
To avoid this, I have inserted an if
statement, and on if the type of file is a static one, it will be served, but html file files will not be served, and instead a 404 error to be returned.
Modify your webpages to point to the new server
After this is done, we only need to include all references to static content in web pages using that link, so if we had a relative url like this <img src="/images/some-image.png" />
now we should use something like this: <img src="http://static.static-yourdomain.com/images/some-image.png" />
.
That's all, now you comply with the recommendation, and cache servers in the middle will save a copy of your images, and further requirements to them will be faster.