Configuring Ghost and nginx for speed

A basic nginx config for Ghost will only be able to serve less than 30 requests per second on a small Digital Ocean or Linode instance. Not very impressive, right?

Run $ ab -c 10 -n 1000 http://yourdomain.com/ to get the results. You should get about 30 requests per second.

But, it is possible to serve five times more requests per second with a minor tweak to nginx.

Define a cache zone in your nginx.conf file by adding the following line to your http {} section:

proxy_cache_path /tmp/nginx-cache levels=1:2 keys_zone=STATIC:75m inactive=24h max_size=512m;

Learn more about this directive.

Then, adjust your server definition to implement caching:

upstream ghost {  
    server unix:/tmp/ghost.sock fail_timeout=0;

    keepalive 60;  # See http://nginx.org/en/docs/http/ngx_http_upstream_module.html#keepalive

}

server {  
    listen 80;

    listen [::]:80;

    server_name yourdomain.com;

    # Do not cache anything from /ghost/ 
    location /ghost {

        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;

        proxy_set_header X-Forwarded-Proto $scheme;

        proxy_set_header X-Real-IP $remote_addr;

        proxy_set_header Host $http_host;


        add_header Cache-Control "no-cache, private, no-store, must-revalidate, max-stale=0, post-check=0, pre-check=0";


        proxy_pass http://ghost;

    }



    # Cache all public pages and posts
    location / {

        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;

        proxy_set_header X-Forwarded-Proto $scheme;

        proxy_set_header X-Real-IP $remote_addr;

        proxy_set_header Host $http_host;



        proxy_cache STATIC;

        proxy_cache_valid 200 10m;

        proxy_cache_valid 404 1m;



        proxy_ignore_headers X-Accel-Expires Expires Cache-Control;

        proxy_ignore_headers Set-Cookie;

        proxy_hide_header Set-Cookie;


        proxy_pass http://ghost;

    }

    # Serve all static content directly with nginx
    location /content/images {

        alias /var/www/<path to ghost>/content/images;

        access_log off;

        expires max;

    }

    location /assets {

        alias /var/www/<path to ghost>/content/themes/<your theme>/assets;

        access_log off;

        expires max;

    }

    location /public {

        alias /var/www/<path to ghost>/core/built/public;

        access_log off; 
        expires max;
    }

    location /ghost/scripts {

        alias /var/www/<path to ghost>/core/built/scripts;

        access_log off;  
        expires max;
    }
}

Reload nginx and test again with $ ab -c 10 -n 1000 http://yourdomain.com/. You should get 130+ requests per second.

Michael Samoylov

Python, JavaScript and Swift Expert with 12+ years of experience.

Vilnius, Lithuania https://monmar.tech

Subscribe to Michael Samoylov

Get the latest posts delivered right to your inbox.

or subscribe via RSS with Feedly!