PageSpeed for Nginx comes in form of module: ngx_pagespeed. It’s important to understand that Nginx has to be manually compiled in order to include PageSpeed module.
Here is our sample configuration which enables PageSpeed module in Nginx server block. It uses Memcached for storing PageSpeed cache. It is also a nice example of using optimized vs. non-optimized page versions as part of your Google Analytics experiment.
Nginx PageSpeed sample configuration
server {
#port to listen on
listen 80;
# server name
server_name domain.com;
# root location
root /var/www/domain.com/public_html;
# access log
access_log /var/log/nginx/domain.com.access.log main;
# PageSpeed
pagespeed on;
# let's speed up PageSpeed by storing it in the super duper fast memcached
pagespeed MemcachedThreads 1;
pagespeed MemcachedServers "localhost:11211";
# show half the users an optimized site, half the regular site
pagespeed RunExperiment on;
pagespeed AnalyticsID UA-XXXXXXXXXX-1;
pagespeed ExperimentVariable 1;
pagespeed ExperimentSpec "id=1;percent=50;level=CoreFilters;enabled=collapse_whitespace,remove_comments;";
pagespeed ExperimentSpec "id=2;percent=50";
# Filter settings
pagespeed RewriteLevel CoreFilters;
pagespeed EnableFilters collapse_whitespace,remove_comments;
# needs to exist and be writable by nginx
pagespeed FileCachePath /var/cache/pagespeed;
# Ensure requests for pagespeed optimized resources go to the pagespeed handler
# and no extraneous headers get set.
location ~ "\.pagespeed\.([a-z]\.)?[a-z]{2}\.[^.]{10}\.[^.]+" {
add_header "" "";
}
location ~ "^/pagespeed_static/" { }
location ~ "^/ngx_pagespeed_beacon$" { }
}
If you don’t use Memcached, you can still use fast memory for storing cache files.
Store ngx_pagespeed cache in memory
Note the FileCachePath directive. It’s a directory which stores cache files. Using strong>tmpfs file system for this directory you can store cache in memory without Memcached.
Create the directory
mkdir -p /var/cache/pagespeed
chown nginx.nginx /var/cache/pagespeed
mount -t tmpfs -o size=100M,mode=0755 tmpfs /var/cache/pagespeed
Make your changes persist across reboot
We want to have the cache directory mounted in memory at boot time, so edit /etc/fstab, and add:
[…]
tmpfs /var/cache/pagespeed tmpfs size=100M,mode=0755 0 0
[…]