【问题标题】:Need to rewrite question marks and equals signs in url需要重写url中的问号和等号
【发布时间】:2010-08-30 14:48:06
【问题描述】:

重写了我的网址。但是我仍然可以访问带有问号和加号的重写网址。

lovelakedistrict.com/lake-district-cottages/?cottages=2/
lovelakedistrict.com/lake-district-cottages/?cottages/2/
lovelakedistrict.com/lake-district-cottages/cottages/2/

以上三个网址是完全相同的页面,我想正确地重写它们,以便它们重定向到正确的结构(最后一个网址)以停止重复网页。

Options +FollowSymlinks
Options +Indexes
RewriteEngine on

RewriteCond %{THE_REQUEST} ^[A-Z]+\ /([^.#?\ ]+)\.php([#?][^\ ]*)?\ HTTP/

RewriteCond %1 !^include/
RewriteRule ^([^.]+)\.php$ /$1 [R=301,L]

RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([^/]+)/$ $1.php

RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([^/]+)/([^/]+)/$ /$1/$2.php

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} !(\.[a-zA-Z0-9]{1,5}|/)$
RewriteRule (.*)$ /$1/ [R=301,L]

RewriteRule ^lake-district-cottages/cottages/([0-9]+) lake-district-cottages.php?cottages=$1

【问题讨论】:

    标签: regex .htaccess mod-rewrite url-rewriting clean-urls


    【解决方案1】:

    试试这些规则:

    RewriteCond %{THE_REQUEST} ^[A-Z]+\ /[^?\ ]*\?[^\ ]+
    RewriteCond %{QUERY_STRING} ^/*([^=&]*[^=&/])/*(&+(.*))$
    RewriteRule ^(.*[^/])/?$ /$1/%1/?%3 [N]
    
    RewriteCond %{THE_REQUEST} ^[A-Z]+\ /[^?\ ]*\?[^\ ]+
    RewriteCond %{QUERY_STRING} ^/*([^=&]*[^=&/])/*$
    RewriteRule ^(.*[^/])/?$ /$1/%1/?%4 [L,R=301]
    
    RewriteCond %{THE_REQUEST} ^[A-Z]+\ /[^?\ ]*\?[^\ ]+
    RewriteCond %{QUERY_STRING} ^/*([^=&]*[^=&/])/*=/*([^&]*[^&/])/*(&+(.*))$
    RewriteRule ^(.*[^/])/?$ /$1/%1/%2/?%4 [N]
    
    RewriteCond %{THE_REQUEST} ^[A-Z]+\ /[^?\ ]*\?[^\ ]+
    RewriteCond %{QUERY_STRING} ^/*([^=&]*[^=&/])/*=/*([^&]*[^&/])/*$
    RewriteRule ^(.*[^/])/?$ /$1/%1/%2/? [L,R=301]
    

    但我想最简单的方法是使用比 mod_rewrite 更强大的语言,例如 PHP:

    $parts = explode('?', $_SERVER['REQUEST_URI'], 2);
    if (count($parts) === 2) {
        $path = rtrim($parts[0], '/');
        parse_str($parts[1], $params);
        foreach ($params as $key => $value) {
            $path .= '/' . (($value === '') ? trim($key, '/') : trim($key, '/') . '/' . trim($value, '/'));
        }
        header('Location: http://example.com'.$path.'/', true, 301);
        exit;
    }
    

    【讨论】:

    • htacccess 规则运行良好,除了我尝试此操作时,例如 lovelakedistrict.com/lake-district-cottages/?cottages=2 它指向 lovelakedistrict.com/lake-district-cottages.php/cottages/2(添加 php 扩展名)- 可以删除吗?感谢您的快速回复
    • @ajfmedia:这可能是由于您使用这些规则的顺序。确保将那些导致外部重定向的规则放在那些只会导致内部重定向的规则之前。
    • Gumbo 还有一件事,有没有一种方法可以阻止影响结果目录中 anthing 的规则,例如lovelakedistrict.com/result/q=windermere,因为它弄乱了我的搜索查询字符串 :(- 虽然它确实整理了它们!
    • @ajfmedia:是的,您可以在每个规则中添加以下条件:RewriteCond %{REQUEST_URI} !^/result/。或者您将此规则放在其他规则之前以跳过它们:RewriteRule ^result/ - [S=4]
    • 嘿,Gumbo,很抱歉打扰你,你能帮我看看其他的吗?- 我不想发布新问题,因为我觉得它们都差不多。
    猜你喜欢
    • 2013-07-26
    • 1970-01-01
    • 2014-05-27
    • 1970-01-01
    • 2013-09-03
    • 2021-08-21
    • 1970-01-01
    • 2012-04-23
    • 1970-01-01
    相关资源
    最近更新 更多