Tag: «seo»
Trimming the trailing slash in URLs with a 301 redirect
event Aug 22, 2011 at 14:37
Why not pin this here — easier to find later, when I need it again. Search engines often treat pages like
arm1.ru/blog/yandex-upal-panika-v-twitter
and
arm1.ru/blog/yandex-upal-panika-v-twitter/
as different pages. So you end up with the same content technically living at two URLs, which isn’t great. Below the cut — code that automatically strips a trailing / via a 301 redirect, so search engines don’t end up with duplicate pages.
<?php
# strip the QUERY_STRING from REQUEST_URI
$uri = $_SERVER['REQUEST_URI'];
if ( false === empty( $_SERVER['QUERY_STRING'] ) )
$uri = str_replace( '?' . $_SERVER['QUERY_STRING'], '', $uri );
# 301 redirect when there is a trailing slash on $uri
if ( substr( $uri, -1 ) == '/' && strlen( $uri ) > 1 ) {
$queryString = '';
if ( false === empty( $_SERVER['QUERY_STRING'] ) )
$queryString = '?' . $_SERVER['QUERY_STRING'];
header( 'Location: ' . substr( $uri, 0, -1 ) . $queryString, true, 301 );
exit;
}