Setting up subdomain cookies, varnish and Nginx for faster asset serving

Updated
Tagged
performance nginx varnish

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:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
server {
    server_name example.com www.example.com;
    root   /var/www/.../example.com/htdocs/;

    # lets add www
    if ($host !~* "^www\.") {
        rewrite  ^/(.*)$  http://www.$host/$1  permanent;
    }

    # serve static files directly
    if ($request_uri ~* "\.(jpe?g|gif|css|png|js|ico|pdf|zip|gz)$") {
        expires 30d;
        break;
    }

    #... other stuff here ...

    }

    server {
        server_name static.example.com;

        if ($request_uri !~* "\.(jpe?g|gif|css|png|js|ico|pdf|zip|gz)$") {
            rewrite ^(.*) http://www.example.com$1 permanent;
            break;
        }

        location / {
            root   /var/www/.../example.com/htdocs/;
            expires max;
            add_header Cache-Control private;
        }
}

Some of the important points to notice:

This setup allows us to set cookies on the www.example.com domain and not static.example.com.

Now you just have to remember to refer to static elements of your page from the static.example.com domain. This is only for items that are unlikely to change like images, CSS, javascript etc.

Varnish’s cache

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.

Conclusion

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.