Search This Blog

Wednesday 12 December 2012

Force URLs to lowercase with Apache rewrite and PHP

Force URLs to lowercase with Apache rewrite and PHP:
#### Add following code to HTaccess ###########
RewriteEngine on
RewriteBase /
# force url to lowercase if upper case is found
RewriteCond %{REQUEST_URI} [A-Z]
# Exclude images being redirected
RewriteCond %{REQUEST_URI} !(\.jpg|\.png|\.gif|\.css|\.jpeg|\.js|\.bmp|\.swf)$ [NC]
# ensure it is not a file on the drive first
RewriteCond %{REQUEST_FILENAME} !-s
RewriteRule (.*) rewrite-strtolower.php?rewrite-strtolower-url=$1 [QSA,L]


######## Create PHP file with name rewrite-strtolower.php and add the followinf code into that file. Place this php file smae folder as htaccess

if(isset($_GET['rewrite-strtolower-url'])) {
    $url = $_GET['rewrite-strtolower-url'];
    unset($_GET['rewrite-strtolower-url']);
    $params = http_build_query($_GET);
    if(strlen($params)) {
        $params = '?' . $params;
    }
    header('Location: http://' . $_SERVER['HTTP_HOST'] . '/' . strtolower($url) . $params, true, 301);
    exit;
}
header("HTTP/1.0 404 Not Found");
die('Unable to convert the URL to lowercase. You must supply a URL to work upon.');

No comments:

Post a Comment