Canonical URLs for a single page site
In this tutorial, I share a handful of .htaccess techniques for implementing canonical URLs for single-page websites. Also referred to as “brochure” sites (among other things). These are all plug-&-play code snippets, just add to any .htaccess-capable site and enjoy the SEO benefits of having canonical URLs. I use these snippets on my sites, such as m0n.co and shapeSpace.
Redirect www and index.php
Single-page sites may suffer from duplicate content if the following URLs display the same page:
http://example.com/
http://example.com/index.html
http://example.com/index.php
http://www.example.com/
http://www.example.com/index.html
http://www.example.com/index.php
You can eliminate duplicate content by redirecting all requests for any of these URLs to the site’s root URL (http://example.com/
). So if you have a one-page site, add the following directives to your site’s root .htaccess file:
# CANONICAL URLS
<IfModule mod_rewrite.c>
RewriteCond %{HTTP_HOST} ^www\.example\.com [NC,OR]
RewriteCond %{THE_REQUEST} /index\.(html|php) [NC]
RewriteRule (.*) http://example.com/ [R=301,L]
</IfModule>
Remember to change both instances of example.com
to your own domain. Once in place, this code will redirect all of the above-listed URLs to the same page, http://example.com/
. Great way to improve the SEO for your site.
Redirect www to non-www
If you only want to redirect www
pages to non-www
pages, use this .htaccess snippet (instead of the previous technique):
# CANONICAL URLS
<IfModule mod_rewrite.c>
RewriteCond %{HTTP_HOST} ^www\.example\.com [NC]
RewriteRule (.*) http://example.com/$1 [R=301,L]
</IfModule>
As before, remember to change both instances of example.com
to your own domain. To redirect instead from non-www
to www
pages, check out my tutorial, canonical www via .htaccess.
Redirect everything
Another, more extreme strategy is to redirect all non-root requests to root. This technique virtually eliminates all 404 Not Found errors, and is great for focusing all traffic on the target page. To do so, add the following directives to your site’s root .htaccess file:
# CANONICAL URLS
<IfModule mod_rewrite.c>
RewriteCond %{HTTP_HOST} ^www\.example\.com$ [NC,OR]
RewriteCond %{THE_REQUEST} !^/?$ [NC]
RewriteCond %{THE_REQUEST} !\.(css|js|jpg|jpe|jpeg|png|gif|zip) [NC]
RewriteRule (.*) http://example.com/ [R=301,L]
</IfModule>
As before, remember to change both instances of example.com
to your own domain. As-is, this technique does not redirect requests for CSS, JavaScript, and some commonly used image files. This is required so your web page has access and can use those particular assets. So if your page requires other types of files (e.g., JSON, Flash, or whatever), you can add their file types to the list on line 5 (separate each file type with a vertical bar |
).