Combine subdomains, cookies, Varnish and Nginx to speed up your site.
Nginx subdomain setup
Firstly, you need to set up a separate subdomain to serve your static, cookie-less content. Let’s say http://static.example.com/. This requires a section in your Nginx server config as follows:
Some of the important points to notice:
- We do a permanent redirect to the ‘www’ subdomain for any requests to example.com.
- We also set a month expires on any static content served from www.example.com just in case.
- The second ‘server’ section catches requests to static.example.com and sets the expires header and the cache control header for longevity. Notice it has the same ‘root’ setting as it is essentially the same as the first server configuration except with different headers. We also catch content requests that should have gone to the main domain and redirect them with a 301 redirect.
This setup allows us to set cookies on the www.example.com domain and not static.example.com.
Varnish (or another proxy) will now be able to cache all content from static.example.com as it has no cookies set. There are ways to set up Varnish to enable caching of cookied content but it is easy to run into trouble there. This method can be done on a per site basis without having to adjust Varnish and have very good results.
By being a little more careful in how you construct your subdomain structure and how your site uses it, you are able to reduce bandwidth and enable other parts of the delivery chain to do their job better.