PHP htaccess Redirect url with query string from uppercase to lowercase

廉价感情. 提交于 2019-12-22 08:24:31

问题


I have this small php script and couple lines in htaccess to redirect urls with query strings from uppercase to lowercase.

However, it redirects uppercase characters in query string to lowercase ones only if there is an uppercase character in the url file or directory part of the url.

Example with uppercase directory:

domain.com/JOBS/?position=Java+Developer

will be redirected to

domain.com/jobs/?position=java+developer

Example with no uppercase in directory or file name, but only in query string:

domain.com/jobs/?position=Java+Developer

will be redirected to

domain.com/jobs/?position=Java+Developer

The first example successfully redirects the directory and the query string to all lowercase.

The second example does not redirect the query string to lowercase, it remains the same.

I can't figure out what to change in the code to get the query string to redirect to lowercase no matter if the directory or file name is uppercase or not.

Here is the code:

htaccess

RewriteEngine On

RewriteBase /

# force url to lowercase if upper case is found
RewriteCond %{REQUEST_URI} [A-Z]
RewriteRule (.*) rewrite-strtolower.php?rewrite-strtolower-url=$1 [QSA,L]

PHP script

<?php
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 = '?' . strtolower($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.');
?>

回答1:


Instead of:

$params = http_build_query($_GET);

use it like this:

$params = strtolower ( http_build_query($_GET) );

And your .htaccess should be:

RewriteEngine On
RewriteBase /

# force url to lowercase if upper case is found
RewriteCond %{REQUEST_URI} [A-Z] [OR]
RewriteCond %{QUERY_STRING} [A-Z]
RewriteRule (.*) rewrite-strtolower.php?rewrite-strtolower-url=$1 [QSA,L,NE]

Since you should be calling your PHP handler for both the cases.



来源:https://stackoverflow.com/questions/26032665/php-htaccess-redirect-url-with-query-string-from-uppercase-to-lowercase

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!