Nginx: WordPress + W3 Total Cache with Page Cache (Disk Enhanced)

Nginx has got one major advantage – it can serve static content very fast and super efficiently. It can provide you a great advantage if your blog gets hit by Digg/Slashdot effect or just very sudden & huge traffic.

Enter, W3 Total Cache – it’s an all in one caching plugin for WordPress. Disk (enhanced) page cache in W3 Total Cache works very well with Nginx as the plugin stores static html files (in gzip form too!) on your server. Nginx can also serve the gzip version of a file if it’s available in the same directory.

To get started, enable disk (enhanced) page cache in your W3TC settings. Once enabled, it’s time to move onto the server side configuration. Open your Nginx configuration and add the following lines in the location / {} block of your code.

 # if the requested file exists, return it immediately
 if (-f $ request_filename) {
         break;
 }
 
 ## W3 Total Cache - Disk (Enhanced) BEGIN
 
 set $ pgcache "";
 
 ##If the request method is GET, then set $ pgcache to "D"
 if ($ request_method = GET) {
 set $ pgcache "$ {pgcache}D";
 }
 
 # We're using pretty permalinks, so bypass caching if there is a query string in the url.
     if ($ args = "") {
 	#Set $ pgcache to "DI" if the query string in the url is empty.
         set $ pgcache "$ {pgcache}I";
     }
 # Bypass cache if the user has the following cookies:
     if ($ http_cookie !~ (comment_author_|wordpress|wordpress_logged_in|wp-postpass_)) {
 	# Set $ pgcache to "DIS" if the above mentioned cookies are not present on user's browser.
         set $ pgcache "$ {pgcache}S";
     }
 
 # Finally, check if W3TC has stored a file for the requested page
     if (-f $ document_root/wp-content/w3tc/pgcache/$ request_uri/_index.html) {
 	
 	# Set $ pgcache to "DISK" if the file exists
         set $ pgcache "$ {pgcache}K";
     }
 
 
 # Check if $ pgcache is equal to "DISK"
     if ($ pgcache = DISK) {
 	#Rewrite the URL to the static stored file and break further actions on this request
         rewrite ^ /wp-content/w3tc/pgcache/$ request_uri/_index.html break;
     }
 
 
 ##W3 Total Cache - Disk (Enhanced) END
 
 # all other requests go to WordPress
 if (!-e $ request_filename) {
         rewrite . /index.php last;
 }

Now that the URL rewriting part’s done, time to enable gzip_static so that Nginx serves the gzip version of the HTML files to the user’s browser.

Edit nginx.conf and add the following line inside the http {} block. If it’s already there, just leave it be.

    
 gzip_static on;

Now that we’re finished editing the nginx configuration, time to restart nginx. I do it by:

service nginx restart

Leave a Reply