Optimize NGINX for WordPress

I decided to switch to pure NGINX, without proxying to Apache to decrease the load on my server. I got the idea from here. Also, my server is too weak to handle two web servers, and NGINX is way lighter, so it was time. Also, I switched to WP Super Cache to boost my site’s speed even more than W3 Total Cache.

Config

First of all, create the usual virtual host with webroot, etc.,etc. Then, to work with WP Super Cache, and browser caching, I used the following config file:

#Browser Caching
location ~* \.(jpg|jpeg|png|gif|ico|css|js){
        expires 30d;
}
location ~*\.(html){
        expires 7d;
}
set $cache_uri $request_uri;

# POST requests and urls with a query string should always go to PHP
if ($request_method = POST) {
    set $cache_uri 'null cache';
}
if ($query_string != "") {
    set $cache_uri 'null cache';
}

# Don't cache uris containing the following segments
if ($request_uri ~* "(/wp-admin/|/xmlrpc.php|/wp-(app|cron|login|register|mail).php
                      |wp-.*.php|/feed/|index.php|wp-comments-popup.php
                      |wp-links-opml.php|wp-locations.php |sitemap(_index)?.xml
                      |[a-z0-9_-]+-sitemap([0-9]+)?.xml)") {

    set $cache_uri 'null cache';
}

# Don't use the cache for logged-in users or recent commenters
if ($http_cookie ~* "comment_author|wordpress_[a-f0-9]+
                     |wp-postpass|wordpress_logged_in") {
    set $cache_uri 'null cache';
}

# Set the cache file
set $cachefile "/wp-content/cache/supercache/$http_host/$cache_uri/index.html";
if ($https ~* "on") {
    set $cachefile "/wp-content/cache/supercache/$http_host/$cache_uri/index-https.html";
}

# Add cache file debug info as header
#add_header X-Cache-File $cachefile;

# Try in the following order: (1) cachefile, (2) normal url, (3) php
location / {
    try_files $cachefile $uri $uri/ /index.php;
}

What does it do?

This config from here and browser caching from here allows for a speedy WordPress setup. It first checks if WP Super cache has the page cached, and if it does, it serves the static HTML, speeding up your site by a lot. If not, it gets passed to PHP-FPM to process it. In order for this to work, you must have WP Super Cache set to mod_rewrite, and you can safely ignore any .htaccess errors it gives you. The browser caching caches images for 30 days, and html for a week, although you can change this to whatever you want.

Feel free to leave any suggestions in the comments!

(Maybe)Related posts:

Leave a Reply

Be the First to Comment!

Notify of
avatar