PageSpeed Module

PageSpeed Configuration

Enabling the Module

PageSpeed contains an "output filter" plus several content handlers.

Note: The location of the configuration file is dependent both on the Linux distribution on which PageSpeed is installed and on whether you're using PageSpeed with Apache or Nginx.

In Apache the configuration file is pagespeed.conf and will be in either:

Debian/Ubuntu: /etc/apache2/mods-available/
CentOS/Fedora: /etc/httpd/conf.d/
In Nginx the configuration typically should go in your nginx.conf which defaults to being in:
/usr/local/nginx/conf/

In Apache PageSpeed is enabled automatically when you install mod_pagespeed, while in Nginx you need to add several lines to your nginx.conf. In every server block where PageSpeed is enabled add:

pagespeed on;

# Needs to exist and be writable by nginx.
pagespeed FileCachePath /var/ngx_pagespeed_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 ~ "^/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; }

Configuring Handlers

When PageSpeed is installed, it automatically enables a default handler permitting it to serve optimized resources, but there are additional handlers you can add to permit you to better monitor PageSpeed's operation:

  1. Statistics: shows server statistics since startup, such as how many resources are being optimized by filters, as well as various latency and cache effectiveness metrics. This handler also lets you view summaries of the configuration being used (in particular which filters are enabled).
  2. Global Statistics: if UsePerVHostStatistics is on this will permit you to access statistics aggregated over all the virtual hosts on the server.
  3. Messages: if MessageBufferSize is set, this will contain a server-wide history of recent logging output from PageSpeed, including messages that are omitted from the server log file based on its log level.
  4. Console: shows graphs of issue metrics over time.
  5. Beacon: can be used by the add_instrumentation filter to report page load times for your sites, which you can then view via the statistics page.

The following is an example Apache configuration that can be used as a guideline:

    # This page shows statistics about the mod_pagespeed module.
    <Location /mod_pagespeed_statistics>
        Order allow,deny
        # One may insert other "Allow from" lines to add hosts that are
        # allowed to look at generated statistics.  Another possibility is
        # to comment out the "Order" and "Allow" options from the config
        # file, to allow any client that can reach the server to examine
        # statistics.  This might be appropriate in an experimental setup or
        # if the Apache server is protected by a reverse proxy that will
        # filter URLs to avoid exposing these statistics, which may
        # reveal site metrics that should not be shared otherwise.
        Allow from localhost
        Allow from 127.0.0.1
        SetHandler mod_pagespeed_statistics
    </Location>

    # Recent log messages. Like statistics, these are generally not to be shown
    # to the public, so this has access controls as well.
    ModPagespeedMessageBufferSize 100000
    <Location /mod_pagespeed_message>
        Order allow,deny
        Allow from localhost
        Allow from 127.0.0.1
        SetHandler mod_pagespeed_message
    </Location>

    # This page lets you view a graphical console displaying statistics about
    # the mod_pagespeed module.
    <Location /pagespeed_console>
        Order allow,deny
        # This can be configured similarly to mod_pagespeed_statistics above.
        Allow from localhost
        Allow from 127.0.0.1
        SetHandler pagespeed_console
    </Location>
Here is the corresponding Nginx configuration:
    # This page shows statistics about the ngx_pagespeed module.
    location /ngx_pagespeed_statistics {
        # One may insert other "allow" lines to add hosts that are
        # allowed to look at generated statistics.  Another possibility is
        # to comment out the "allow" and "deny" options from the config
        # file, to allow any client that can reach the server to examine
        # statistics.  This might be appropriate in an experimental setup or
        # if the Nginx server is protected by a reverse proxy that will
        # filter URLs to avoid exposing these statistics, which may
        # reveal site metrics that should not be shared otherwise.
        allow 127.0.0.1;
        deny all;
    }

    # Recent log messages. Like statistics, these are generally not to be shown
    # to the public, so this has access controls as well.
    pagespeed MessageBufferSize 100000;
    location /ngx_pagespeed_message {
        allow 127.0.0.1;
        deny all;
    }

    # This page lets you view a graphical console displaying statistics about
    # the ngx_pagespeed module.  As with statistics and messages, you may
    # want access control.
    location /pagespeed_console {
        allow 127.0.0.1;
        deny all;
    }

Apache-Specific Configuration

Setting up the Output Filter

The output filter is used to parse, optimize, and re-serialize HTML content that is generated elsewhere in the Apache server.

# Direct Apache to send all HTML output to the mod_pagespeed output handler.
AddOutputFilterByType MOD_PAGESPEED_OUTPUT_FILTER text/html

Note: mod_pagespeed automatically enables mod_deflate for compression.

Turning the module on and off

To turn mod_pagespeed ON, insert as the top line of pagespeed.conf:

ModPagespeed on

There are two ways to disable mod_pagespeed. To disable HTML rewriting but continue to serve .pagespeed. resources and parse query options (for instance for ?ModPagespeed=on) put this line in your configuration:

ModPagespeed off

To completely disable mod_pagespeed (.pagespeed. resources will result in 404s) use the following line:

Note: New feature as of 1.3.25.1

ModPagespeed unplugged

The on and off values can be used in .htaccess files, <Directory> scopes, query parameters, and headers. The unplugged value can only be used in the top-level Apache configuration and in virtual hosts.

Support for Apache 2.4.x

mod_pagespeed is compatible with Apache 2.2.x and Apache 2.4.x series, versions 2.4.2 and newer. Please note that Apache 2.4.1 has a bug that may cause stability problems in combination with mod_pagespeed, so use with 2.4.1 is strongly discouraged.

As Apache 2.4 is not API compatible with 2.2, support for it is provided via a separate module binary, mod_pagespeed_ap24.so instead of the usual mod_pagespeed.so. The configuration provided in our binary packages will normally load the right module version automatically. However, if you upgrade the CentOS packages from an earlier version, the needed configuration change may not get applied on top of a user-customized pagespeed.conf, so you may need to adjust the LoadModule line manually.

Source builds with mod_pagespeed-provided Apache headers will build both 2.2.x and 2.4.x binaries as well, and you will need to add a LoadModule line matching the server version in use, or use a pattern similar to:

<IfModule !mod_version.c>
  LoadModule version_module /usr/lib/apache2/modules/mod_version.so
</IfModule>

<IfVersion < 2.4>
  LoadModule pagespeed_module /usr/lib/apache2/modules/mod_pagespeed.so
</IfVersion>
<IfVersion >= 2.4.2>
  LoadModule pagespeed_module /usr/lib/apache2/modules/mod_pagespeed_ap24.so
</IfVersion>
to auto-detect. Builds against system Apache headers will only be compatible with that version family, and will always produce a single module named mod_pagespeed.so.

Nginx-Specific Configuration

Turning the module on and off

To turn ngx_pagespeed ON, put anywhere in your http or server block:

pagespeed on;

To turn ngx_pagespeed OFF, use off:

pagespeed off;
This is equivalent to the "unplugged" setting for mod_pagespeed, and entirely disables ngx_pagespeed.

Respecting Vary Headers

In order to maximize the number of resources that PageSpeed can rewrite, by default the module does not respect Vary: User-Agent and other Vary headers on resource files, such as JavaScript and css files. By disregarding the Vary headers, PageSpeed is able to keep the size of the cache down. PageSpeed will always respect Vary: Accept-Encoding, regardless of this setting. PageSpeed will also always respect Vary headers on HTML files, regardless of this setting.

If a site has resources that legitimately vary on User-Agent, or on some other attribute, then in order to preserve that behavior, you must add

Apache:
ModPagespeedRespectVary on
Nginx:
pagespeed RespectVary on;

to your configuration file.

Please note that turning on this option will disable optimization of any resources with Vary headers, apart from Vary: Accept-Encoding.

Honoring no-transform Cache-Control Headers

Note: New feature as of 1.6.29.3

By default, PageSpeed does not rewrite resources that have Cache-Control: no-transform set in the Response Header. This is true for all types of resources, such as JavaScript, images, CSS etc. By respecting Cache-Control: no-transform headers, PageSpeed cannot optimize resources that could otherwise be rewritten.

To optimize resources irrespective of Cache-Control: no-transform headers, you must add

Apache:
ModPagespeedDisableRewriteOnNoTransform off
Nginx:
pagespeed DisableRewriteOnNoTransform off;

to your configuration file.

Please note that PageSpeed will always respect Cache-Control: no-transform headers on HTML files irrespective of the setting. And also, PageSpeed will always retain the Cache-Control: no-transform headers on the resource irrespective of the setting so that the downstream cache control mechanisms do not get affected.

Lower-casing HTML element and attribute names

HTML is case-insensitive, whereas XML and XHTML are not. Web performance Best Practices suggest using lowercase keywords, and PageSpeed can safely make that transformation in HTML documents.

In general, PageSpeed knows whether a document is HTML or not via Content-Type tags in HTTP headers, and DOCTYPE. However, many web sites have Content-Type: text/html for resources that are actually XML documents.

If PageSpeed lowercases keywords in XML pages, it can break the consumers of such pages, such as Flash. To be conservative and avoid breaking such pages, PageSpeed does not lowercase HTML element and attribute names by default. However, you can sometimes achieve a modest improvement in the size of compressed HTML by enabling this feature with:

Apache:
ModPagespeedLowercaseHtmlNames on
Nginx:
pagespeed LowercaseHtmlNames on;

These directives can be used in location-specific configuration sections.

Risks

This switch is only risky in the presence of XML files that are incorrectly served with Content-type: text/html. Lower-casing XML element and attribute may affect whatever software is reading the XML.

Preserving HTML caching headers

By default, PageSpeed serves all HTML with Cache-Control: no-cache, max-age=0 because the transformations made to the page may not be cacheable for extended periods of time.

If you want to force PageSpeed to leave the original HTML caching headers you can add:

Apache:
ModPagespeedModifyCachingHeaders off
Nginx:
pagespeed ModifyCachingHeaders off;

Note: We do not suggest you turn this option off. It breaks PageSpeed's caching assumptions and can lead to unoptimized HTML being served from a proxy caches set up in front of the server. If you do turn it off, we suggest that you do not set long caching headers to HTML or users may receive stale or unoptimized content.

Specifying the value for the PageSpeed header

By default, PageSpeed adds an header, X-Mod-Pagespeed in Apache, X-Page-Speed in Nginx, with the version of PageSpeed being used. This directive lets you specify the value to use instead:

Apache:
ModPagespeedXHeaderValue "Powered By mod_pagespeed"
Nginx:
pagespeed XHeaderValue "Powered By ngx_pagespeed";

Note: You cannot suppress the injection of this header. This is because it is used to prevent infinite loops and unnecessary rewrites when PageSpeed fetches resources from an origin that also uses PageSpeed.

Location-Specific Configuration

With an .htaccess file (Apache), <Direcory> scope (Apache), or location block (Nginx) you can control most of the PageSpeed directives. Note, however, that the file-matching is only relevant to the HTML file, and not to any of the resources referenced from the HTML file. To restrict resources by directory, you must use the PageSpeed Allow and Disallow directives, using full paths or wildcards in those directives.

Warning: Resources and the HTML files that reference them must have the same options. If they differ you may see poor performance and inconsistent application of options.

In Apache, the advantage of .htaccess is that it can be used in environments where the site administrator does not have access to the server configuration. However, there is a significant per-request overhead from processing .htaccess files. See The Apache HTTP Server Documentation:

Note: You should avoid using .htaccess files completely if you have access to the httpd main server config file. Using .htaccess files slows down your Apache server. Any directive that you can include in a .htaccess file is better set in a <Directory> block, as it will have the same effect with better performance.

Virtual hosts are generally a better way of configuring multiple sites on the same server.

Using PageSpeed With Virtual Hosts

Note: New feature as of 1.1.23.1

By default PageSpeed installs itself for the entire server including all VirtualHosts (Apache) or server blocks (Nginx). If you want the exact same PageSpeed configuration for all VirtualHosts, you can just use the default configuration layout. You can, however, use different settings for some of the virtual hosts if you so chose.

In each virtual host, PageSpeed configures itself as follows:

  • If there are no PageSpeed-specific configuration options, then the global configuration is used.
  • If there are PageSpeed-specific options in the virtual host:
    • In Nginx, or in Apache when InheritVHostConfig is on, the global PageSpeed configuration will be inherited into the virtual host, which can override it as needed.
    • In Apache when InheritVHostConfig is off the virtual host starts off with an entirely clean PageSpeed configuration. This means if you turn PageSpeed on in that host, you will also need to repeat FileCachePath and any other settings.
If you are using version 1.1.23.1 or newer, a convenient approach is to put the common settings in the global configuration and put only site-specific configuration in each host's section. In Apache this requires setting ModPagespeedInheritVHostConfig on in the global configuration.
Apache:
ModPagespeed On
ModPagespeedInheritVHostConfig on
ModPagespeedFileCachePath "/var/cache/mod_pagespeed/"
ModPagespeedEnableFilters combine_css,combine_javascript
# Direct Apache to send all HTML output to the mod_pagespeed
# output handler.
AddOutputFilterByType MOD_PAGESPEED_OUTPUT_FILTER text/html

NameVirtualHost *:80
<VirtualHost *:80>
  DocumentRoot /www/example1
  ServerName www.example1.com
  ModPagespeedMapRewriteDomain cdn.example1.com *example.com
</VirtualHost>

<VirtualHost *:80>
  DocumentRoot /www/example2
  ServerName www.example2.org
  ModPagespeedMapRewriteDomain cdn.example2.org *example.org
  # Don't want combine_css here
  ModPagespeedDisableFilters combine_css
</VirtualHost>

<VirtualHost *:80>
  DocumentRoot /www/example3
  ServerName www.example3.org
  # mod_pagespeed off for this virtual host
  ModPagespeed Off
</VirtualHost>
Nginx:
http {
  pagespeed On;
  pagespeed FileCachePath "/var/cache/ngx_pagespeed/";
  pagespeed EnableFilters combine_css,combine_javascript;

  server {
    listen 80;
    server_name www.example1.com;
    root /www/example1;
    pagespeed MapRewriteDomain cdn.example1.com *example.com;
  }

  server {
    listen 80;
    server_name www.example2.org;
    root /www/example2;
    pagespeed MapRewriteDomain cdn.example2.org *example.org;
    # Don't want combine_css here
    pagespeed DisableFilters combine_css;
  }

  server {
    listen 80;
    server_name www.example3.org;
    root /www/example3;

    # mod_pagespeed off for this virtual host
    pagespeed off;
  }

If you're using a version older than 1.1.23.1, you will need to repeat the common settings in each virtual host. Putting the common settings in a separate file and then using the Include directive is a good way of making such installs manageable. Note that you should not copy over AddOutputFilterByType MOD_PAGESPEED_OUTPUT_FILTER text/html to the virtual hosts if that is in the global scope as copying it over would end up adding it multiple times.

Virtual hosts and statistics

Note: New feature as of 1.1.23.1

You can also chose whether PageSpeed aggregates its statistics over all virtual hosts (the default), or to keeps separate counts for each. You can chose the latter by specifying UsePerVHostStatistics on. In that case, /mod_pagespeed_statistics or /ngx_pagespeed_statistics will show the data for whatever virtual host is being accessed. If you do turn per-virtual host statistics on, you can still access the aggregates under /mod_pagespeed_global_statistics or /ngx_pagespeed_global_statistics. In Apache this requires exporting a handler:
ModPagespeedUsePerVHostStatistics on
<Location /mod_pagespeed_global_statistics>
   Order allow,deny
   Allow from localhost
   Allow from 127.0.0.1
   SetHandler mod_pagespeed_global_statistics
</Location>

Preserve URL Relativity

Note: New feature as of 1.7.30.1

Previous versions of PageSpeed would rewrite relative URLs into absolute URLs. This wastes bytes and can cause problems for sites that sit behind HTTPS terminators.

With PreserveUrlRelativity on, PageSpeed will keep URLs the way they were found. Some examples:

Original URL Rewritten URL
foo/bar.png foo/bar.png.pagespeed.ic.Hash.png
/bar.png /bar.png.pagespeed.ic.Hash.png
//example.com/bar.png //example.com/bar.png.pagespeed.ic.Hash.png
http://example.com/bar.png http://example.com/bar.png.pagespeed.ic.Hash.png

To enable this option, add:

Apache:
ModPagespeedPreserveUrlRelativity on
Nginx:
pagespeed PreserveUrlRelativity on;

to your configuration file.

Note: This option will be enabled by default in future versions of PageSpeed and eventually the option will be removed entirely.

Authentication required

You need to be signed in with Google+ to do that.

Signing you in...

Google Developers needs your permission to do that.