【问题标题】:url rewriting with htaccess? [duplicate]用 htaccess 重写 url? [复制]
【发布时间】:2013-06-18 00:08:30
【问题描述】:

我的问题: 我想写一个 .htaccess 规则。 www.asdf.com/city.php?city=New-Yorkwww.asdf.com/New-York 而且我还有其他页面,例如 www.asdf.com/country.php?country=USA 我想显示为 www.asdf.com/USAwww.asdf.com/state.php?country=LA 我想显示为www.asdf.com/LA

很困惑如何做到这一点。

【问题讨论】:

    标签: .htaccess url url-rewriting


    【解决方案1】:

    如果您希望 3 个完全不同的事物具有相同的 url,则必须使用 php 页面来“检测”它是什么类型的“事物”并将您的请求“路由”到特定页面。

    以下(未经测试的)两个规则会将上面列出的所有“丑陋”网址重定向到一个花哨的 url,并将这个花哨的 url 重定向到一个 php 页面,该页面决定了它应该用于请求的页面。 %2 是对 RewriteCondition 中的第二个捕获组的反向引用。尾随 ? 清除查询字符串。

    RewriteCond %{QUERY_STRING} (city|country)=([^&]*)
    RewriteRule (country\.php|city\.php|state\.php) %2? [R=301,L]
    
    RewriteRule ^([^/]*)$ myRouter.php?url=$1 [END]
    

    使用文件myRouter.php 类似:

    <?php
      $url = $_GET['url'];
    
      if( isCity( $url ) ) {
        $city = $url;
        include( 'city.php' );
        exit();
      } elseif( isCountry( $url ) ) {
        $country = $url;
        include( 'country.php' );
        exit();
      }
      #etc....
    ?>
    

    更合乎逻辑的是为不同的事物使用不同的花哨的 url,例如/country/USAcountry.php?country=USA/state/LAstate.php?country=LA/city/New-Yorkcity.php?city=New-York

    这可以通过以下(未经测试的)htaccess 轻松完成,并生成更多逻辑 URL:

    RewriteCond %{QUERY_STRING} (city|state|country)=([^&]*)
    RewriteRule ^(country|city|state)\.php$ $1/%2? [R=301,L]
    
    RewriteRule ^(country|city|state)/(.*)$ $1.php?$1=$2 [END]
    

    【讨论】:

      猜你喜欢
      • 2014-03-27
      • 2017-06-30
      • 2017-01-26
      • 2014-11-02
      • 2013-06-23
      • 1970-01-01
      • 2015-02-03
      • 2023-03-23
      • 1970-01-01
      相关资源
      最近更新 更多