Tiny WordPress Insights

W3 Total Cache configuration for Nginx-Apache server stack

During the past 24 hours, there were two people had the following situation and were looking for a solution. Their use-case is…

I’m currently using a Nginx frontend / Apache backend setup. The W3 Total Cache plugin detects Apache and will only show me the Apache rewrite rules.

Here’s another quote from the other person who was looking for a similar solution…

The nginx.conf file does not exist. W3 Total Cache plugin detects that Apache is running – thus gives me the rewrites for that webserver instead. I am using Nignx in front of Apache – not a Nginx/PHP-FPM solution

Interesting, but not uncommon. So, I dived in and modified my existing Nginx rules for WP Super Cache plugin and provided a unique solution.

Here’s the full working solution that applies to any Nginx-Apache server stack with W3 Total Cache plugin…


server {
  server_name domainname.com;
  listen 80;

  root "/path/to/wordpress/core";
  index index.php;

  location / {
    error_page 418 = @cachemiss;
    recursive_error_pages on;

    if ($request_method = POST) { return  418; }

    if ($query_string != "") { return 418; }

    if ($http_cookie ~* "comment_author | wp\-postpass | w3tc_logged_out | wordpress_logged_in | wptouch_switch_toggle") { return 418; }

    try_files "/wp-content/cache/page_enhanced/$host/$uri/_index.html" =418;

    # optional code
    # expires 30m;
    # add_header "X-W3TC-Cache" "HIT :)";
  }

  location @cachemiss {
    # pass the requests to backend (Apache)

    # optional header
    # add_header "X-W3TC-Cache" "Miss :(";
  }

  # other directives
  # for example
  location ~* \.php$ {
    # pass all PHP requests to Apache
  }

  # another example
  location /wp-admin {
    # pass all "wp-admin" requests to Apache
  }
}

Since, it follows the best practices of using an if statement in Nginx, this code should work flawlessly. You may still need to fill certain blocks in it to make it work for your specific situation.

Exit mobile version