ngx_pagespeed configuration tutorial for 90+ pagespeed score

What is ngx_pagespeed?

Website speed is important for search engine optimization and user experience.Google has incorporated site speed in Google search algorithm.You can see Site speed being reporting in Google Analytics dashboard.Also Google Adsense shows PageSPeed Score in Site Health section of Scorecard.

Google is not only reporting site speed but also have provided tools to improve it and measure it.

It has started PageSpeed insights which visitors can use to locate problem areas (in terms of speed) on your website.It has also started PageSpeed module for Apache and Nginx.This module fixes majority of speed road blocks and speeds up your website.

You just need to install it and perform simple configuration.ngx_pagespeed is PageSpeed module for Nginx web server.In this post I will cover ngx_pagespeed.

The installation part of pagespeed module differs in case of Apache and Nginx.The configuration commands are different.But you can configure Apache PageSpeed module using this tutorial.The filters used in this tutorial is applicable to Nginx as well as Apache.The only difference will be the commands used in case of Nginx and Apache.

Why is ngx_pagespeed important?

ngx_pagespeed is single solution which allows you to take care of most website performance issues.You just have to install it and configure properly to take advantage of all features.The result is improved performance and good Google PageSpeed and Yahoo YSlow scores.The optimization features available in ngx_pagespeed can be clubbed into below categories

  • CSS optimization (CSS is Cascading Style Sheet) example combine and minify CSS.
  • JS optimization ( JS is JavaScript ) example combine and minify JS and defer load JS.
  • Image Optimization example lazy load images and optimize images.
  • Other Optimization features like DNS prefetch,HTML optimization,URL prefetcher.
  • Different Cache Types like Shared cache,PDF cache and File Cache.

Above I have outlined some of optimization features.There are other features as well.They can more or less be clubbed into any one of above category.For example Inline CSS and Move CSS to head can be grouped into CSS optimization,Inline JS can be grouped in JS optimization.Similarly HTML optimization has many sub parts like remove comments,remove white space and others.

Now’s lets see how to install ngx_pagespeed on your Nginx server.We will also discuss configuration to use above features.

Installing ngx_pagespeed

The ngx_pagespeed github readme file provides detailed instruction on installation.Below I am referring to commands mentioned on that page along with some of the modifications and details.

Installing on Debian and Ubuntu


In case you are using Debian and Ubuntu then installing ngx_pagespeed is very easy process.You do not have to follow instructions mentioned on Github page of ngx_pagespeed.I would recommend using this method.


Step 1


Add below lines to /etc/apt/sources.list file (at the end)

deb http://packages.dotdeb.org wheezy all
deb-src http://packages.dotdeb.org wheezy all

Step 2

wget http://www.dotdeb.org/dotdeb.gpg
sudo apt-key add dotdeb.gpg

Step 3

apt-get update;apt-get install nginx-common nginx-extras

Just running these few commands will install Nginx server along with ngx_pagespeed module.In future you just need to run below commands to update your Nginx web server and ngx_pagespeed.

apt-get update;apt-get upgrade

Installing from source

Installing dependencies

The module has some dependencies so before installing the module we need to install the dependencies.Installing dependencies is very easy and is matter to one command (as taken from ngx_pagespeed github page).If you are already logged in using root account there is no need to use sudo in front of the commands.

Command for RedHat,CentOS and Fedora

$ sudo yum install gcc-c++ pcre-dev pcre-devel zlib-devel make

Command for Debian and Ubuntu

$ sudo apt-get install build-essential zlib1g-dev libpcre3 libpcre3-dev

Download ngx_pagespeed

After installing dependencies the next step is to download ngx_pagespeed and nginx web server.Even if you already have nginx server installed it is good to download latest version of nginx.You have to build nginx server from source to install ngx_pagespeed.Below commands mentioned on github page of ngx_pagespeed work quite well

$ cd ~
$ wget https://github.com/pagespeed/ngx_pagespeed/archive/release-1.6.29.3-beta.zip
$ unzip release-1.6.29.3-beta.zip # or unzip release-1.6.29.3-beta
$ cd ngx_pagespeed-release-1.6.29.3-beta/
$ wget https://dl.google.com/dl/page-speed/psol/1.6.29.3.tar.gz
$ tar -xzvf 1.6.29.3.tar.gz # expands to psol/
  • First command moves you to Home directory of the user you have logged in with
  • Download latest version of nginx_pagespeed from github.I would be updating the commands to reflect latest version but you can check official ngx_pagespeed github page for latest version (You can check commands in How to Build section and use them they will be referring to latest version.In current case latest version is 1.6.29.3.
  • Unzip the downloaded zip and change directory to it.You need to download psol and extract that.

Downloading nginx

Now we need to latest version of nginx web server using command as shown below

$ wget http://nginx.org/download/nginx-1.4.1.tar.gz
$ tar -xvzf nginx-1.4.1.tar.gz
$ cd nginx-1.4.1/

Above commands download nginx web server,extracts it and change your current directory to it.

Configuring nginx


Now we need to build nginx with ngx_pagespeed support.Above stated procedure remains same whether you are installing nginx for first time or have it already installed.Now run below commands to instal nginx with ngx_pagespeed support

$ ./configure --add-module=$HOME/ngx_pagespeed-release-1.6.29.3-beta
	       --prefix=/etc/nginx
              --conf-path=/etc/nginx/nginx.conf
              --error-log-path=/var/log/nginx/error.log
	      --http-log-path=/var/log/nginx/access.log
	      --lock-path=/var/lock/nginx.lock
              --pid-path=/var/run/nginx.pid
	      --with-ipv6

Above command adds module nginx_pagespeed using (–add-module).We are also setting the installation path.The installation paths used above are default paths on Debian.You can change it according to your operating system.The command does not change

Pre installed nginx notes

Now if you have nginx already installed on your system it is better to use current directory and file names.nginx will not overwrite your configuration files.So you should not worry about that and give file name and directory name of your currently installed nginx in parameters above.

In above command I have mentioned some of the parameters only.You can check all the parameters supported using below command and then pass those parameters as shown above

$ ./configure --help

After entering above commands enter below commands (for all operating systems)

$ make
$ make install

Configuring ngx_pagespeed for best performance

ngx_pagespeed supports lots of parameter and proper configuration is required for optimal performance and to get best out of it.

Configuring nginx.conf file

nginx.conf file is central configuration file for nginx server.We will add ngx_pagespeed related changes to this file if we want that functionality to enable for every website hosted on that server.Below is nginx.conf file optimized for best performance.You can copy the code given below and paste it in your configuration file

	##
	# Pagespeed rules
	##

	pagespeed On;
	pagespeed FileCachePath "/dev/shm/ngx_cache";
	pagespeed FileCacheSizeKb 25600;
	pagespeed FileCacheCleanIntervalMs 3600000;
	pagespeed FileCacheInodeLimit 500000;
	pagespeed RewriteLevel PassThrough;
	pagespeed EnableFilters canonicalize_javascript_libraries,extend_cache,extend_cache_pdfs,combine_css,combine_javascript,move_css_above_scripts,insert_dns_prefetch,rewrite_javascript,rewrite_images,prioritize_critical_css,rewrite_css,rewrite_style_attributes,convert_meta_tags,lazyload_images,collapse_whitespace,move_css_to_head,remove_comments,remove_quotes,defer_javascript,inline_css,inline_javascript;
	pagespeed UseNativeFetcher on;
	resolver 8.8.8.8;
	pagespeed LRUCacheKbPerProcess     2048;
	pagespeed LRUCacheByteLimit        8192;
	pagespeed CreateSharedMemoryMetadataCache "/dev/shm/ngx_shared" 6400;
	pagespeed CssInlineMaxBytes 1024;
	pagespeed JsInlineMaxBytes 1024;

In above code you can see two references /dev/shm/ngx_shared and /dev/shm/ngx_cache.These directories are in RAM.The files cached will be in RAM and performance will be better.You can choose to cache your files in RAM or you can choose to cache them on file system.If you are caching them on RAM you need to do extra configuration that we will see later in this post.

You can use your web server directory for caching as well.

The directory you are using above should be accessible by Nginx.You can use /usr/share/nginx/www/cache as well.I prefer it in RAM but if RAM memory of your VPS does not allow this then web server directory is my next preference.

Creating Cache directories

You need to create directories mentioned above.Now in case you want to use RAM (tmpfs) file system then follow below steps.If you want to use normal file system like /var directory then you just need to skip first step only (rest of the procedure will be same)

Check RAM file system

$ free -m

Run command free -m to check tmpfs file system on your server.for example let the directory is /dev/shm

Create Directories

$ mkdir /dev/shm/ngx_cache
$ mkdir /dev/shm/ngx_shared

Run the mkdir directory to create the directory ngx_cache and ngx_shared within the directory /dev/shm or /var/cache or any other directory suitable to you.

Change ownership

$chown www-data:www-data /dev/shm/ngx_cache
$chown www-data:www-data /dev/shm/ngx_shared

Change the owner of the directories to www-data (nginx) using below command.You need to replace /dev/shm/nginx_cache or /dev/shm/ngx_shared according to your directory names.

Modification to startup scripts

This step is only applicable if you are using RAM as your cache (that is using /dev/shm) directory to host the cache files.The problem is the directories inside /dev/shm gets deleted after server reboot.This will cause nginx issue and your website will become offline.

So you need to create these directories and set the permissions to www-data during system reboot.

For this purpose you will have to add below commands in initial startup script.

Open the file /etc/rc.local and paste below lines (if your directory names is same as shown below else change it to your directory names (only if you have made these directories in RAM).

$ mkdir /dev/shm/ngx_cache
$ mkdir /dev/shm/ngx_shared
$chown www-data:www-data /dev/shm/ngx_cache
$chown www-data:www-data /dev/shm/ngx_shared

The last line will be exit 0 (already present in the file).

Testing ngx_pagespeed configuration

Loading Configuration

Now you will have to restart your nginx server to that above changes take effect.To restart nginx server enter below command

$/etc/init.d/nginx restart

Sometimes restarting nginx does not work if you have nginx pre installed on your system.In that case you will have to restart your server.

Testing Configuration

Just browse you web page and then see the source of you web page.Your CSS file and JS files will have pagespeed in their name.You can also check you cache directories created above.They will have some entries in them (matching your domain name for which pagespeed has been enabled).

Consider sharing the post in case you found it useful

7 thoughts on “ngx_pagespeed configuration tutorial for 90+ pagespeed score

  1. Nice setup,

    Do you use this for WordPress? and btw do you also this 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}.[^.]+" {
    access_log off; log_not_found off;
    add_header Pragma public;
    add_header Cache-Control "public, max-age=600";
    add_header "" "";
    }

    location ~ "^/ngx_pagespeed_static/" { }
    location ~ "^/ngx_pagespeed_beacon$" { }
    location /ngx_pagespeed_statistics {
    allow 127.0.0.1;
    deny all;
    }
    location /ngx_pagespeed_global_statistics {
    allow 127.0.0.1;
    deny all;
    }
    location /ngx_pagespeed_message {
    allow 127.0.0.1;
    deny all;
    }

    I was trying to set this but I'm having trouble with the rewrites… the try_files I need on location / to make wordpress work seem to give a 404 for the pagespeed pages (ex: pagespeed_console)

    " try_files $uri $uri/ /index.php?q=$uri&$args;"

    that's what I'm using and afaik it should work!

    • Thanks for enriching the post with your valuable comment.

      Yes I am using this setup for WordPress.The modified code as shared by you is coded in Server block (Sites-Avaible folder).Now for the try files I am using below code

      location / {
      try_files $uri $uri/ /index.php?$args;
      }

      Hope this helps.

  2. Hello and thanks,

    great info for my projekt. 😉

    Best regards from good old germany. 😉

    Olaf

    • Good to know you found it useful

      • Hi Esha,

        in new pagespeed/nginx Version is pagespeed CreateSharedMemoryMetadataCache out of date, it is a global setting and ignore (tell me the option nginx -t). 😉

        Nice Day and sleep well. 😉
        Olaf

    • This post is old and due to lack of time was unable to update it.Thanks for pointing things out

Leave a Comment