Skip to content

Static caching homepage in FastCGI environments

Mark Croxton edited this page Mar 20, 2017 · 10 revisions

The problem

In some hosting environments (where PHP is run as CGI, FastCGI or PHP-FPM on recent versions of Apache 2.4.x) it is necessary to add an additional ? to ExpressionEngine’s default .htaccess rule when removing index.php from URLs, so that the path is passed as a query string to index.php (see: Removing index.php from URLs):

RewriteRule ^(.*)$ /index.php?/$1 [L]

Should you use this rule and wish to static cache the homepage you will find that, once the homepage is cached, every other URL is rewritten to the homepage when using Stash's default static caching mod_rewrite rules.

Fortunately you can use this workaround to cache both internal pages and the homepage.

The solution

When caching the homepage template, specify a custom uri for the cached file using the uri="" parameter. For example:

 {exp:stash:static logged_out_only="yes" uri="home"}

Now add this block of rules above the original Stash static caching rules:

#################################################################################
# START STASH STATIC CACHE - HOMEPAGE

# last rewrite pass
RewriteCond %{ENV:REDIRECT_STATUS} 200
RewriteCond %{REQUEST_URI} ^/static_cache/[site_id]/home
RewriteRule ^ - [L,ENV=HOMEPAGE]

# Homepage
RewriteCond $1 ^$
RewriteCond %{REQUEST_METHOD} ^GET
RewriteCond %{HTTP:ACT} !=^$
RewriteCond %{HTTP:X-Requested-With} !=XMLHttpRequest 
RewriteCond %{QUERY_STRING} !^(css|ACT|URL|preview)
RewriteCond %{HTTP_COOKIE} !exp_sessionid [NC]
RewriteCond %{DOCUMENT_ROOT}/static_cache/[site_id]/home/index.html -f
RewriteRule ^$ /static_cache/[site_id]/home/index.html [L,ENV=HOMEPAGE]

<IfModule mod_headers.c>

# add headers
Header set Cache-Control "max-age=0, no-cache, no-store, must-revalidate" env=HOMEPAGE
Header set Pragma "no-cache" env=HOMEPAGE
Header set Expires "Wed, 11 Jan 1984 05:00:00 GMT" env=HOMEPAGE 

</IfModule>

# END STASH STATIC CACHE RULES - HOMEPAGE
#################################################################################

As with the original rules, replace [site_id] with the id number of your site (usually 1 unless you are using MSM).

Note that in some environments (notably, Nexcess hosting) you may need to adjust the rewrite condition that ignores POST requests. See this thread for details: http://expressionengine.stackexchange.com/questions/18550/stash-static-caching-not-ignoring-posts-like-i-think-it-should

Clone this wiki locally