【问题标题】:Handle similar URLs without loosing case-sensivity在不区分大小写的情况下处理相似的 URL
【发布时间】:2016-06-25 10:35:22
【问题描述】:

我刚刚意识到我的主机 URL 区分大小写。

表示/homepage、/Homepage和/homePage是不同的URL,这是有问题的。

我可以强制任何 URL 为小写,这样可以解决我的问题,但这并不是我想要的。

我想知道是否可以将/homepage 的任何变体(即:/hOMEpaGe,/HOMEPAGE,/hOmEpAgE,...)重定向到 /homePage(注意区分大小写)

我不知道我是通过服务器配置更好地处理它还是通过操作$_SERVER[REQUEST_URI]进入php文件。

感谢您对此的任何想法!

【问题讨论】:

  • “这是有问题的”——为什么?是否有很多人输入您网站的 URL 而不是点击链接,并且有无法控制的按 shift 键的冲动?大多数网站的 URL 中的路径段都区分大小写,这通常不是问题。

标签: php apache url-rewriting


【解决方案1】:

当然可以使用strtolower、stristr()、str_replace() 和header() 的组合对 Bootstrap 文件(例如 index.php)进行重定向,如下所示:

<?php
    // ASSUMING THE BASE URI IS KNOWN
    $baseURI    = "http://www.my-domain.com";
    // CONVERT ALL CHARACTERS IN THE $_SERVER['REQUEST_URI'] TO LOWER-CASES
    $uri        = strtolower($_SERVER['REQUEST_URI']);
    $rdURI      = str_replace("homepage", "homePage", $uri);


    // USE EITHER A SWITCH OR IF CONDITIONAL LOGIC TO SET THE URI
    if(stristr($uri, "homepage")){  // REDIRECT ANY THING WITH HOMEPAGE TO: homePage
        $rdURI  = str_replace("homepage", "homePage", $uri);
    }else if(stristr($uri, "another-uri-1")){
        $rdURI  =  str_replace("another-uri-1", "another-URI-1", $uri);
    }else if(stristr($uri, "another-uri-2")){
        $rdURI  = str_replace("another-uri-2", "another-URI-2", $uri);
    }else if(stristr($uri, "yet-another-uri")){
        $rdURI  = str_replace("yet-another-uri", "yet-Another-URI", $uri);
    }else{
        // DEFAULT TO THE HOMEPAGE IF ALL ELSE FAIL
        // THIS DECISION IS UP TO YOU AS YOU MIGHT NOT NEED IT TO WORK THIS WAY...
        $rdURI  = str_replace("homepage", "homePage", $uri);
    }

    // REDIRECT TO THE NEW URI...
    header("location: " . $rdURI);
    exit;

    // OR REDIRECT TO THE NEW URI WITH BASE URI...
    header("location: " . $baseURI . DIRECTORY_SEPARATOR . $rdURI);
    exit;

【讨论】:

    【解决方案2】:

    与在 PHP 中进行重定向相比,在较低级别处理此问题总是一个更好的主意。

    如果要实现这一点,首先你需要声明一个 RewriteMap

    # Add RewriteMap for redirecting to lowercase URIs
    <IfModule mod_rewrite.c>
    RewriteMap lc int:tolower
    </IfModule>
    

    然后只需创建 RewriteRule 以将大写 URL 重定向到小写 URL。

    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_URI} [A-Z]
    RewriteRule ^(.*)$ ${lc:$1} [R=301,L]
    

    【讨论】:

      【解决方案3】:

      使用 .htaccess [NC] 表示不区分大小写:

      RewriteCond %{REQUEST_URI} /phpMyAdmin [NC]
      

      lmgtfy:https://perishablepress.com/case-insensitive-redirectmatch/

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2019-05-22
        • 1970-01-01
        • 2019-06-26
        • 2011-03-08
        • 1970-01-01
        • 1970-01-01
        • 2014-03-25
        相关资源
        最近更新 更多