Kerry Jones
Kerry Jones

Reputation: 21848

Nginx - W3 Caching Rules on Wordpress

To start off, I'm very new to nginx.

I am trying to implement gzip compression and browser caching rules on a series of Nginx servers that are hosting wordpress sites. I got code from the following page that is supposed to be put in the nginx.conf file: http://codex.wordpress.org/Nginx

W3 Total Cache Rules

# BEGIN W3TC Browser Cache
gzip on;
gzip_types text/css application/x-javascript text/richtext image/svg+xml text/plain text/xsd text/xsl text/xml image/x-icon;
location ~ \.(css|js)$ {
    expires 31536000s;
    add_header Pragma "public";
    add_header Cache-Control "max-age=31536000, public, must-revalidate, proxy-revalidate";
    add_header X-Powered-By "W3 Total Cache/0.9.2.3";
}
location ~ \.(html|htm|rtf|rtx|svg|svgz|txt|xsd|xsl|xml)$ {
    expires 180s;
    add_header Pragma "public";
    add_header Cache-Control "max-age=180, public, must-revalidate, proxy-revalidate";
    add_header X-Powered-By "W3 Total Cache/0.9.2.3";
}
location ~ \.(asf|asx|wax|wmv|wmx|avi|bmp|class|divx|doc|docx|exe|gif|gz|gzip|ico|jpg|jpeg|jpe|mdb|mid|midi|mov|qt|mp3|m4a|mp4|m4v|mpeg|mpg|mpe|mpp|odb|odc|odf|odg|odp|ods|odt|ogg|pdf|png|pot|pps|ppt|pptx|ra|ram|swf|tar|tif|tiff|wav|wma|wri|xla|xls|xlsx|xlt|xlw|zip)$ {
    expires 31536000s;
    add_header Pragma "public";
    add_header Cache-Control "max-age=31536000, public, must-revalidate, proxy-revalidate";
    add_header X-Powered-By "W3 Total Cache/0.9.2.3";
}
# END W3TC Browser Cache
# BEGIN W3TC Skip 404 error handling by WordPress for static files
if (-f $request_filename) {
    break;
}
if (-d $request_filename) {
    break;
}
if ($request_uri ~ "(robots\.txt|sitemap(_index|[0-9]+)?\.xml(\.gz)?)") {
    break;
}
if ($request_uri ~* \.(css|js|html|htm|rtf|rtx|svg|svgz|txt|xsd|xsl|xml|asf|asx|wax|wmv|wmx|avi|bmp|class|divx|doc|docx|exe|gif|gz|gzip|ico|jpg|jpeg|jpe|mdb|mid|midi|mov|qt|mp3|m4a|mp4|m4v|mpeg|mpg|mpe|mpp|odb|odc|odf|odg|odp|ods|odt|ogg|pdf|png|pot|pps|ppt|pptx|ra|ram|swf|tar|tif|tiff|wav|wma|wri|xla|xls|xlsx|xlt|xlw|zip)$) {
    return 404;
}
# END W3TC Skip 404 error handling by WordPress for static files

I tried placing it in the http { section and restart the server, but it said locations are in the wrong place.

Does it need to go in the server {? Or what is the best place to put this?

Thanks!

Upvotes: 0

Views: 779

Answers (1)

cobaco
cobaco

Reputation: 10556

from http://nginx.org/en/docs/http/ngx_http_core_module.html#location we learn that the accepted contexts for a location block are server and location.

So yes you need to put the location blocks inside a server block (or nested inside another location block but your config doesn't do that)

the gzip bits have an allowed context of "http, server, location, if in location" according to http://nginx.org/en/docs/http/ngx_http_gzip_module.html#gzip, so you can put them in either your http or server block.

Upvotes: 1

Related Questions