Using Pagespeed with Nginx

Pagespeed is a quick way to optimize your site following web best practices. It is available as a module for Apache and Nginx. Installing this module in Apache is easy as:


sudo yum install at # if you do not already have 'at' installed
sudo rpm -U mod-pagespeed-*.rpm

To install Nginx, we need to compile the Nginx source in order to include Pagespeed module (please see this article for instructions). For Nginx configuration, please follow this guide.

Pagespeed Nginx configuration

  1. Create Pagespeed global configuration:

    
    mkdir -p /etc/nginx/apps/pagespeed
    vi /etc/nginx/apps/pagespeed/core.conf
    
    

    ... the content:

    
    ## PageSpeed configurations
    pagespeed on;
    pagespeed ProcessScriptVariables on;
    pagespeed FetchWithGzip on;
    
    ## PageSpeed filter settings
    pagespeed RewriteLevel CoreFilters;
    pagespeed RespectVary off;
    pagespeed DisableRewriteOnNoTransform off;
    pagespeed SupportNoScriptEnabled false;
    pagespeed ModifyCachingHeaders on;
    pagespeed ListOutstandingUrlsOnError on;
    pagespeed MaxCacheableContentLength -1;
    pagespeed FileCachePath /var/cache/nginx/pagespeed;
    pagespeed FileCacheSizeKb            102400;
    pagespeed FileCacheCleanIntervalMs   3600000;
    pagespeed FileCacheInodeLimit        500000;
    pagespeed LRUCacheKbPerProcess     1024;
    pagespeed LRUCacheByteLimit        16384;
    
    ## Speed up PageSpeed by storing it in the super duper fast memcached
    pagespeed MemcachedThreads 1;
    pagespeed MemcachedServers "localhost:11211";
    
    ## PageSpeed admin pages configuration
    pagespeed UsePerVhostStatistics on;
    pagespeed Statistics on;
    pagespeed StatisticsLogging on;
    pagespeed StatisticsLoggingIntervalMs 60000;
    pagespeed StatisticsLoggingMaxFileSizeKb 1024;
    pagespeed MessageBufferSize 100000;
    pagespeed LogDir /var/log/pagespeed;
    pagespeed StatisticsPath /ngx_pagespeed_statistics;
    pagespeed GlobalStatisticsPath /ngx_pagespeed_global_statistics;
    pagespeed MessagesPath /ngx_pagespeed_message;
    pagespeed ConsolePath /pagespeed_console;
    pagespeed AdminPath /pagespeed_admin;
    pagespeed GlobalAdminPath /pagespeed_global_admin;
    
    ## PageSpeed Cache Purge
    pagespeed EnableCachePurge on;
    pagespeed PurgeMethod PURGE;
    pagespeed DownstreamCacheRewrittenPercentageThreshold 95;
    
    

    Note: Don't forget to include "/etc/nginx/apps/pagespeed/core.conf" in your "/etc/nginx/nginx.conf".

    
    include apps/pagespeed/core.conf;
    
    
  2. Create the PageSpeed folders that should exists:

    
    mkdir /var/cache/nginx/pagespeed
    chown nginx:root /var/cache/nginx/pagespeed
    chmod 700 /var/cache/nginx/pagespeed
    mkdir /var/log/pagespeed
    chown nginx. /var/log/pagespeed
    
    
  3. Create site specific Pagespeed filter Nginx configuration:

    
    vi /etc/nginx/apps/pagespeed/optimize.conf
    
    

    Copy and paste following configuration into it:

    
    ## PageSpeed configurations
    pagespeed FetchHttps enable,allow_self_signed;
    pagespeed MaxCacheableContentLength -1;
    
    ## Resource filters
    include apps/pagespeed/resource_filters.conf;
    
    ## Miscellaneous
    pagespeed EnableFilters add_instrumentation;
    pagespeed EnableFilters insert_dns_prefetch;
    
    ## Cache
    pagespeed EnableFilters extend_cache;
    pagespeed EnableFilters extend_cache_pdfs;
    pagespeed EnableFilters local_storage_cache;
    
    ## 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$ps_dollar" { }
    
    ## PageSpeed Admin paths
    include apps/pagespeed/admin_ui.conf;
    
    
    
    vi /etc/nginx/apps/pagespeed/admin_ui.conf
    
    

    Copy and paste following configuration into it:

    
    ## PageSpeed Admin UI paths
    location /ngx_pagespeed_statistics {
      auth_basic "Restricted";
      auth_basic_user_file key/.htpasswd-users;
    }
    location /ngx_pagespeed_global_statistics {
      auth_basic "Restricted";
      auth_basic_user_file key/.htpasswd-users;
    }
    location /ngx_pagespeed_message {
      auth_basic "Restricted";
      auth_basic_user_file key/.htpasswd-users;
    }
    location /pagespeed_console {
      auth_basic "Restricted";
      auth_basic_user_file key/.htpasswd-users;
    }
    location ~ ^/pagespeed_admin {
      auth_basic "Restricted";
      auth_basic_user_file key/.htpasswd-users;
    }
    location ~ ^/pagespeed_global_admin {
      auth_basic "Restricted";
      auth_basic_user_file key/.htpasswd-users;
    }
    
    
    
    vi /etc/nginx/apps/pagespeed/resource_filters.conf
    
    

    Copy and paste following configuration into it:

    
    ## Text / HTML
    pagespeed EnableFilters combine_heads;
    pagespeed EnableFilters collapse_whitespace;
    pagespeed EnableFilters convert_meta_tags;
    pagespeed EnableFilters elide_attributes;
    pagespeed EnableFilters pedantic;
    pagespeed EnableFilters remove_comments;
    pagespeed EnableFilters remove_quotes;
    pagespeed EnableFilters trim_urls;
    
    ## JavaScript
    pagespeed EnableFilters combine_javascript;
    pagespeed EnableFilters canonicalize_javascript_libraries;
    pagespeed EnableFilters inline_javascript;
    
    ## CSS
    pagespeed EnableFilters outline_css;
    pagespeed EnableFilters combine_css;
    pagespeed EnableFilters inline_import_to_link;
    pagespeed EnableFilters inline_css;
    pagespeed EnableFilters inline_google_font_css;
    pagespeed EnableFilters move_css_above_scripts;
    pagespeed EnableFilters move_css_to_head;
    pagespeed EnableFilters prioritize_critical_css;
    pagespeed EnableFilters rewrite_css;
    pagespeed EnableFilters fallback_rewrite_css_urls;
    pagespeed EnableFilters rewrite_style_attributes_with_url;
    
    ## Images
    pagespeed EnableFilters dedup_inlined_images;
    pagespeed EnableFilters inline_preview_images;
    pagespeed EnableFilters resize_mobile_images;
    pagespeed EnableFilters lazyload_images;
    pagespeed EnableFilters inline_images;
    pagespeed EnableFilters convert_gif_to_png;
    pagespeed EnableFilters convert_jpeg_to_progressive;
    pagespeed EnableFilters recompress_jpeg;
    pagespeed EnableFilters recompress_png;
    pagespeed EnableFilters recompress_webp;
    pagespeed EnableFilters strip_image_color_profile;
    pagespeed EnableFilters strip_image_meta_data;
    pagespeed EnableFilters jpeg_subsampling;
    pagespeed EnableFilters convert_png_to_jpeg;
    pagespeed EnableFilters resize_images;
    pagespeed EnableFilters resize_rendered_image_dimensions;
    pagespeed EnableFilters convert_jpeg_to_webp;
    pagespeed EnableFilters convert_to_webp_lossless;
    pagespeed EnableFilters insert_image_dimensions;
    pagespeed NoTransformOptimizedImages on;
    pagespeed EnableFilters sprite_images;
    
    

    Those are my set of configuration and of course you can remove some filters that you don't need. Check the https://developers.google.com/speed/pagespeed/module/filter-head-add for complete list of PageSpeed filters.

  4. Create the password file ".htpasswd-users":

    
    htpasswd -d -b -c /etc/nginx/key/.htpasswd-users myusername mypassword
    
    

    Change the "myusername" with your desired username and "mypassword" with your own password.

  5. Include the "/etc/nginx/apps/pagespeed/optimize.conf" for site:

    
    vi /etc/nginx/sites-enabled/example.com.conf
    
    

    And append following line inside the server context:

    
    include apps/pagespeed/optimize.conf;
    
    

    - OR -

    If you are following this guide and you want PageSpeed configuration common to all of your websites, this line include apps/pagespeed/optimize.conf; is recommended to be appended at /nginx/apps/drupal/common_server_context.conf.

  6. Restart Nginx service:

    
    systemctl restart nginx.service
    
    

    You can access the Pagespeed statistics for a specific site at http://example.com/ngx_pagespeed_statistics and for global http://example.com/ngx_pagespeed_global_statistics

After I applied Pagespeed, my Bounce rate improved:
Bounce rate improved

Comments

the directory pagespeed in /etc/nginx/apps/ is empty. So pagespeed is not installed and How do I solve this?

I have removed nginx and then installed the compiled nginx and Pagespeed package.
The module is now added and checked that with nginx -V.
But if I do a curl on the localhost, then the module is not loaded:

[root@webserver SOURCES]# curl -I -p http://localhost
HTTP/1.1 200 OK
Server: nginx/1.12.2
Date: Mon, 05 Feb 2018 22:03:36 GMT
Content-Type: text/html
Content-Length: 612
Last-Modified: Mon, 05 Feb 2018 20:52:45 GMT
Connection: keep-alive
ETag: "5a78c41d-264"
Accept-Ranges: bytes

Please help, I'm still a novice...

yes I have followed the steps and also included the optimize.conf in common_server_context.conf. Maybe because I don;t have a site installed yet?
Can you explain for example where to install a site (Wordpress)? In /home or in /etc/nginx/prod?

Theoretically, pagespeed should work even on localhost. The site install location path does not matter in pagespeed. Please execute this test command:
  
curl -I -p http://localhost?PageSpeed=on
  
... you should see something like this among the output:
  
x-page-speed:1.12.34.3-0
  
If you didn't see that line in the output after executing the mentioned test command, you are not calling the pagespeed configuration properly in your nginx configuration. You should review it thoroughly (you might have missed something).

Very good your tips, I think your google bounce rate has reduced
When did you start putting tutorial in this profile?

I would be happy to see this tutorial using redis :)

Thank you. The lower Google bounce rate is the better.

I wrote this tutorial last September 3, 2015.

I haven't use redis yet but I will look on that in my free time. Thanks.

I believe there is not a good practice to inline and outline in same time. These options both for JS and CSS should be use individually one by one. Let me know how the above setup is working in production, and if so maybe some updates to it?

Add new comment

Restricted HTML

  • Allowed HTML tags: <a href hreflang> <em> <strong> <cite> <blockquote cite> <code> <ul type> <ol start type> <li> <dl> <dt> <dd> <h2 id> <h3 id> <h4 id> <h5 id> <h6 id>
  • Lines and paragraphs break automatically.