RewriteRule仅用于文件名的小写转换

时间:2016-03-01 23:02:39

标签: php regex .htaccess redirect url-rewriting

我正在尝试将Capital Case文件名重定向到服务器上的小写文件,保留完整的目录大小写。

我无法访问httpd.conf。

我发现this使用php和RewriteRule处理这个技巧,但在我的情况下,我无法捕获$_SERVER['HTTP_HOST']/base/filename之间的目录,所以我在导致apache失败的重定向。

规则是:

RewriteEngine on
RewriteBase /

# force url to lowercase if upper case is found
RewriteCond %{REQUEST_URI} [A-Z]
# ensure it is not a file on the drive first
RewriteCond %{REQUEST_FILENAME} !-s
RewriteRule (?=([^\/])*(\.htm|\.html|\.jpg))(.*) rewrite-strtolower.php?rewrite-strtolower-url=$3 [QSA,L]

RegEx (?=([^\/])*(\.htm|\.html|\.jpg))(.*)捕获并仅将文件名传递给进行真正重定向的php脚本:

<?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 = '?' . $params;
    }
    header('Location: http://' . $_SERVER['HTTP_HOST'] . '/base/' . 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.');

我需要测试的URL示例是:

http://test.com/base/some Folder/some Other subfolder/Some-File-Name.jpg

需要的结果:

http://test.com/base/some Folder/some Other subfolder/some-file-name.jpg

有没有办法纠正事情以捕获我丢弃的URL部分?

修改:我的整个.htaccess可见here.

1 个答案:

答案 0 :(得分:1)

不要使用确切的例子。您也可以在PHP中获得完整路径。您不需要捕获URI。您可以在PHP中使用$dates.selectable = false来获取完整路径。我会做这样的事情。 只需将完整的请求发送到php,然后在那里处理它。

REQUEST_URI

// php文件

RewriteEngine on
RewriteBase /

#don't do anything if php file is directly requested. 
RewriteRule ^rewrite-strtolower\.php - [L]

# force url to lowercase if upper case is found
RewriteCond %{REQUEST_URI} [A-Z]
# ensure it is not a file on the drive first
RewriteCond %{REQUEST_FILENAME} !-s
RewriteRule . /rewrite-strtolower.php [L]