-
-
Save joshbuchea/ba40228fbd1f96e413b1 to your computer and use it in GitHub Desktop.
/** | |
* Changes the requested URL to lowercase. | |
* | |
* Only if URL does not include a filename or query variable. | |
*/ | |
function force_lowercase_urls() { | |
// Grab requested URL | |
$url = $_SERVER['REQUEST_URI']; | |
// If URL contains a period, halt (likely contains a filename and filenames are case specific) | |
if ( preg_match('/[\.]/', $url) ) { | |
return; | |
} | |
// If URL contains a question mark, halt (likely contains a query variable) | |
if ( preg_match('/[\?]/', $url) ) { | |
return; | |
} | |
if ( preg_match('/[A-Z]/', $url) ) { | |
// Convert URL to lowercase | |
$lc_url = strtolower($url); | |
// 301 redirect to new lowercase URL | |
header('Location: ' . $lc_url, TRUE, 301); | |
exit(); | |
} | |
} |
I've tried your solution, and in general it works fine. Only reason why I don't use it is that if the URL has a query string the base URL without the query string is not set to lowercase. In this form it's pitily not suitable for my demands.
Is there a reason you're not using SCRIPT_URI and QUERY_STRING from $_SERVER?
I now set up a short script on my own to fit my needs, so far it works fine for me:
if( !empty($_SERVER['SCRIPT_URI']) && $_SERVER['SCRIPT_URI'] !== strtolower($_SERVER['SCRIPT_URI']) ) { $redirect = strtolower($_SERVER['SCRIPT_URI']); if(!empty($_SERVER['QUERY_STRING'])) { $redirect.= "?".$_SERVER['QUERY_STRING']; } header('Location: ' . $redirect, TRUE, 301); exit(); }
@SinnlosS no good reason, this is just an old gist I created 5 years ago and probably didn't spend much time slapping together 😄
I have a free plugin in the WP marketplace with this same functionality and I may have resolved the issue there but I can't recall:
This is an excellent solution. ;)