且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

PHP htaccess的重定向URL与查询字符串从大写改为小写

更新时间:2023-02-23 08:27:17

相反的:

  $ PARAMS = http_build_query($ _ GET);
 

使用这样的:

  $ PARAMS =用strtolower(http_build_query($ _ GET));
 

和你的.htaccess应该是:

  RewriteEngine叙述上
的RewriteBase /

#强制URL为小写,如果大写被发现
的RewriteCond%{REQUEST_URI} [A-Z] [OR]
的RewriteCond%{QUERY_STRING} [A-Z]
重写规则(。*)改写-strtolower.php?重写,用strtolower-URL = $ 1 [QSA,L,NE]
 

既然你应该叫你的PHP处理程序,这两种情况。

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.');
?>

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.