.htaccess Code Snippets

Specify a Vary: Accept-Encoding header

This is a requirement for Google’s pagespeed. This is needed because there are bugs in some public proxies that may lead to compressed versions of your resources being served to users that don’t support compression. Specifying the Vary: Accept-Encoding header instructs the proxy to store both a compressed and uncompressed version of the resource.

Add the following to your .htaccess file:

<IfModule mod_headers.c>
  <FilesMatch "\.(js|css|xml|gz)$">
    Header append Vary: Accept-Encoding
  </FilesMatch>
</IfModule>

Force Trailing Slash

Add the following to your .htaccess file to force a / at the end of the URL.

<IfModule mod_rewrite.c>
RewriteCond %{REQUEST_URI} /+[^.]+$
RewriteRule ^(.+[^/])$ %{REQUEST_URI}/ [R=301,L]
</IfModule>

Remove the WWW from the Beginning of the URL

Add the following to your .htaccess file to remove the WWW. from the beginning of the URL.

# Rewrite www.example.com → example.com
<IfModule mod_rewrite.c>
    RewriteCond %{HTTPS} !=on
    RewriteCond %{HTTP_HOST} ^www.(.+)$ [NC]
    RewriteRule ^ http://%1%{REQUEST_URI} [R=301,L]
</IfModule>

Force the WWW at the Beginning of the URL

Add the following to your .htaccess file to force the WWW. at the beginning of the URL.

# Rewrite example.com → www.example.com
# Use with caution, as this may cause subdomains to forward as well.
<IfModule mod_rewrite.c>
    RewriteCond %{HTTPS} !=on
    RewriteCond %{HTTP_HOST} !^www..+$ [NC]
    RewriteCond %{HTTP_HOST} !=localhost [NC]
    RewriteCond %{HTTP_HOST} !=127.0.0.1
    RewriteRule ^ http://www.%{HTTP_HOST}%{REQUEST_URI} [R=301,L]
</IfModule>