Running a WooCommerce store can be resource-intensive, especially when dealing with high traffic or complex queries. By configuring Nginx’s FastCGI cache, you can significantly boost performance, reduce server load, and provide faster page load times for your users. However, WooCommerce is a dynamic system, particularly when it comes to the cart and checkout pages, which must show personalized information in real time.
Table of Contents
Caching these pages without careful consideration can lead to serving outdated or incorrect information to users. This guide will show you how to fine-tune your Nginx caching configuration so that only the necessary pages are cached while ensuring that dynamic pages are served correctly.
Let’s dive into the detailed process of setting up and optimizing WooCommerce with Nginx’s FastCGI cache.
Why Use Nginx’s FastCGI Cache for WooCommerce?
WooCommerce generates dynamic content that requires frequent updates (e.g., cart items, checkout, user accounts), and caching can lead to serving outdated information if not handled properly. Nginx’s FastCGI cache can reduce the load on your server by caching static content for your visitors, which will make your website significantly faster. However, you need to configure Nginx correctly to avoid issues on dynamic pages.
Step 1: Install and Configure Nginx FastCGI Cache
Before diving into WooCommerce-specific optimizations, you’ll need to set up Nginx’s FastCGI cache.
How to Enable FastCGI Cache?
1. Create a cache directory on your server:
sudo mkdir /var/cache/nginx
sudo chown -R www-data:www-data /var/cache/nginx
2. Open the Nginx configuration file for editing:
sudo nano /etc/nginx/nginx.conf
3. Add these FastCGI cache settings:
fastcgi_cache_path /var/cache/nginx levels=1:2 keys_zone=FASTCGI:100m inactive=60m use_temp_path=off;
fastcgi_cache_key "$scheme$request_method$host$request_uri";
4. Reload Nginx to apply the new configuration:
sudo systemctl reload nginx
Now that you have FastCGI cache enabled, the next step is to fine-tune it to work with WooCommerce.
Step 2: Skip Cache for Dynamic WooCommerce Pages
Certain WooCommerce pages like the cart, checkout, and account pages should never be cached because they need to display personalized data. To avoid caching these critical pages, we need to set specific rules in the Nginx configuration.
Add these rules to your Nginx configuration:
1. Open your site’s configuration file:
sudo nano /etc/nginx/sites-available/your-site.conf
2. Add the following block to skip cache for WooCommerce’s dynamic pages:
map $request_uri $skip_cache {
default 0;
"~^/cart" 1;
"~^/checkout" 1;
"~^/my-account" 1;
"~^/shop" 1; # Add any other relevant dynamic/custom pages
}
Explanation: This code tells Nginx to skip the cache for the cart, checkout, and account pages. These pages require real-time data and should not serve cached content.
3. Modify the FastCGI cache settings to apply these cache rules:
location ~ \.php$ {
fastcgi_cache_bypass $skip_cache;
fastcgi_no_cache $skip_cache;
fastcgi_cache FASTCGI;
fastcgi_cache_valid 200 60m;
fastcgi_cache_valid 404 1m;
fastcgi_pass php-fpm;
include fastcgi_params;
}
4. Save the file and reload Nginx:
sudo systemctl reload nginx
This ensures that critical WooCommerce pages are always served fresh, while other pages can still benefit from caching.
Step 3: Optimize Cache Behavior for WooCommerce Cart Items
By default, WooCommerce uses cookies to track the number of items in a user’s cart. To ensure the cart updates correctly, we need to skip the cache only when necessary, rather than disabling it site-wide.
Skip Cache When Cart is Not Empty (Only on Critical Pages)
Instead of skipping the cache site-wide when an item is added to the cart, we can restrict this rule to key pages such as the cart and checkout pages. This way, the rest of the site (like product pages) can still benefit from caching, even if the user has items in their cart.
1. Add the following block to skip cache when cart items exist only on specific pages:
if ($request_uri ~* "/cart|/checkout|/my-account") {
if ($cookie_woocommerce_items_in_cart != "0") {
set $skip_cache 1;
}
}
Explanation: This code ensures that Nginx only skips the cache when the user has items in their cart and is on one of the critical pages. The rest of the site, including product pages, will remain cached.
Step 4: Handle “Add to Cart” Query Strings
When users add an item to their cart via the ?add-to-cart
query string, Nginx should skip caching to ensure the cart is updated in real-time.
Add this rule to handle query strings related to adding items to the cart:
if ($arg_add-to-cart != "") {
set $skip_cache 1;
}
Explanation: This rule tells Nginx to bypass the cache whenever a user adds a product to their cart. It ensures that the cart is updated dynamically, even on product pages.
Step 5: Optimize Session Handling with WooCommerce
WooCommerce uses session cookies to track users and their activities. To make sure each user’s session is handled correctly, we need to adjust the cache key to include session cookies.
Update your FastCGI cache configuration to include WooCommerce session cookies:
location ~ \.php$ {
set $rt_session "";
if ($http_cookie ~* "wc_session_cookie_[^=]*=([^%]+)%7C") {
set $rt_session wc_session_cookie_$1;
}
fastcgi_cache_key "$scheme$request_method$host$request_uri$rt_session";
try_files $uri =404;
}
Explanation: This configuration ensures that Nginx includes the WooCommerce session cookie in the cache key. This prevents one user from seeing another user’s session data.
Step 6: Further Nginx Optimizations for WooCommerce
Enable GZIP Compression
GZIP compression reduces the file size of your website, which speeds up page load times. You can enable it with the following configuration:
gzip on;
gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript image/svg+xml;
gzip_vary on;
gzip_min_length 256;
Rate Limiting for Security
To prevent DDoS attacks or brute-force attempts on your WooCommerce store, consider rate-limiting:
nginx
limit_req_zone $binary_remote_addr zone=one:10m rate=1r/s;
limit_req zone=one burst=5;
This configuration adds rate-limiting to requests, which can help improve security and protect your server from malicious traffic.
Final Config Summary: WooCommerce Optimization with Nginx FastCGI Cache
Below is the full Nginx configuration with all the optimizations from Step 1 to Step 6. This ensures that your WooCommerce store benefits from caching where appropriate, while dynamic pages like the cart and checkout are always served fresh.
This configuration goes into your Nginx configuration file, typically located at /etc/nginx/sites-available/your-site.conf
:
# https://blorax.com/en/blog/how-to-optimize-woocommerce-with-nginxs-fastcgi-cache-a-step-by-step-guide/
# Blorax Digital Marketing. 2024. No guarantee or warranty applies for this file. Use at your own risk.
# Step 1: FastCGI Cache Settings (optional)
fastcgi_cache_path /var/cache/nginx levels=1:2 keys_zone=FASTCGI:100m inactive=60m use_temp_path=off;
# Step 6: Enable Brotli (optional) and/or Gzip Compression
brotli on;
brotli_comp_level 5;
brotli_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript image/svg+xml;
gzip on;
gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript image/svg+xml;
gzip_vary on;
gzip_min_length 256;
# Step 6: Rate limiting to prevent DDoS and brute-force attacks
limit_req_zone $binary_remote_addr zone=one:10m rate=1r/s;
limit_req zone=one burst=5;
# SSL Optimization (recommended)
ssl_protocols TLSv1.2 TLSv1.3;
ssl_prefer_server_ciphers on;
ssl_ciphers "EECDH+AESGCM+AES128:EECDH+AESGCM+AES256:!AES128-SHA:!AES256-SHA:!aNULL:!eNULL:!EXPORT:!DES:!RC4:!3DES:!MD5:!PSK:!SRP:!DSS";
ssl_ecdh_curve X25519:secp384r1;
ssl_session_cache shared:SSL:10m;
ssl_session_tickets off;
server {
listen 80;
server_name your-site.com;
root /var/www/your-site;
# Step 2: Skip Cache on Critical WooCommerce Pages
map $request_uri $skip_cache {
default 0;
"~^/cart" 1;
"~^/checkout" 1;
"~^/my-account" 1;
"~^/shop" 1; # Add any other relevant dynamic/custom pages
}
# Security Headers for Protection (recommended)
add_header X-XSS-Protection "1; mode=block" always;
add_header Content-Security-Policy "default-src 'self'; script-src 'self' 'unsafe-inline'; object-src 'none';" always;
add_header Referrer-Policy "no-referrer-when-downgrade" always;
add_header Strict-Transport-Security "max-age=63072000; includeSubDomains; preload" always;
# Disable XML-RPC Access for Security (optional)
location = /xmlrpc.php {
deny all;
}
# Step 3: PHP Requests Handling (including cache and WooCommerce logic)
location ~ \.php$ {
include fastcgi_params;
fastcgi_pass php-fpm;
# Step 3: Skip Cache When Cart is Not Empty (WooCommerce pages)
set $skip_cache 0;
if ($request_uri ~* "/cart|/checkout|/my-account") {
if ($cookie_woocommerce_items_in_cart != "0") {
set $skip_cache 1;
}
}
# Step 4: Handle Add-to-Cart Query Strings
if ($arg_add-to-cart != "") {
set $skip_cache 1;
}
# Step 5: Optimize WooCommerce Session Handling
set $rt_session "";
if ($http_cookie ~* "wc_session_cookie_[^=]*=([^%]+)%7C") {
set $rt_session wc_session_cookie_$1;
}
# Step 5: Define the unique cache key for the FastCGI cache after $rt_session is set
fastcgi_cache_key "$scheme$request_method$host$request_uri$rt_session";
# Apply caching rules (optional)/(recommended)
fastcgi_cache_bypass $skip_cache;
fastcgi_no_cache $skip_cache;
fastcgi_cache FASTCGI;
fastcgi_cache_valid 200 60m;
fastcgi_cache_valid 404 1m;
# Buffer and timeout settings for FastCGI (optional)/(recommended)
fastcgi_buffer_size 16k;
fastcgi_buffers 4 16k;
fastcgi_busy_buffers_size 32k;
fastcgi_temp_file_write_size 32k;
fastcgi_read_timeout 300;
# Error handling
try_files $uri =404;
}
# Step 6: Static file optimizations (recommended)
location ~* \.(jpg|jpeg|gif|css|png|js|ico|html)$ {
expires 30d;
log_not_found off;
add_header Cache-Control "public, max-age=2592000";
}
# Additional Optimizations for Long Sessions (recommended)
add_header X-Frame-Options "SAMEORIGIN";
add_header X-Content-Type-Options "nosniff";
add_header Expect-CT "enforce, max-age=30";
# Don't log errors for /robots.txt but allow access (recommended)
location = /robots.txt {
allow all;
log_not_found off;
more_clear_headers Server;
more_clear_headers "Pragma";
}
# Deny public access to wp-config.php for security (recommended)
location ~* wp-config.php {
deny all;
}
}
Once all changes are made, save the file and reload Nginx to apply your new configurations:
sudo systemctl reload nginx
Conclusion: Maximizing WooCommerce Performance with Nginx
By following these steps, you’ve optimized your WooCommerce store to work efficiently with Nginx’s FastCGI cache. This setup ensures that dynamic pages like the cart and checkout are always served fresh, while other pages benefit from caching to improve speed and reduce server load. Your WooCommerce store is now more responsive, secure, and ready to handle high traffic without sacrificing user experience.
This balance between caching and dynamic functionality helps create a faster shopping experience for your customers, leading to better conversion rates and higher SEO rankings.
If you encounter any issues or need further customization, feel free to reach out Blorax Team!
Leave a Reply