Search code examples
cachingnginxamazon-cloudfrontcache-control

How to configure Nginx with CloudFront to benefit from CloudFront's caching?


I have a website with Wordpress. This website is hosted on Nginx & php-fpm. I added CloudFront to increase performance and decrease origin server load.

However, I can see in Chrome's developer tools console that all resources has Miss from CloudFront value in x-cache header.

I'm not sure how I should configure Nginx & CloudFront to work properly and benefit from caching.

I believe it's all about proper headers that should be set by Nginx (eg. Cache-Control: public for images?). I can't find any examples that would cover all cases and wouldn't mess up Wordpress Admin Panel (this one shouldn't be cached, right?).


Solution

  • A quick fix could be to install the WP Super Cache plugin; has CDN support besides other things.

    In the Nginx side you could do something like this for static content:

    location ~* \.(?:ico|css|js|gif|jpe?g|png)$ {
        expires 30d;
        add_header Pragma public;
        add_header Cache-Control "public";
    }
    

    You can add as many directives, not necesary only images, for example:

    location ~* \.(?:cur|gz|svg|mp4|ogg|ogv|webm|htc)$ {
         access_log off;
         add_header Cache-Control "max-age=2592000";
         #... more options
    }
    

    The ?: prefix is a 'non-capturing' mark, meaning we don't require the pattern to be captured into $1 which should help improve performance.

    You can find more info about the Nginx expires option here.