【问题标题】:custom redirection only for special format via htaccess通过 htaccess 仅针对特殊格式的自定义重定向
【发布时间】:2016-08-21 12:04:45
【问题描述】:

您好,我想通过 htaccess 自定义重定向。

仅适用于这种格式

www.example.com/index.php?id=abc --> www.example.com/abc

但对于任何其他格式没有变化:

例如

www.example.com/index.php?id=abc&id2=qaz --> www.example.com/index.php?id=abc&id2=qaz

这段代码(@starkeen 编写)做得很好:

RewriteEngine on

#1)Redirect "/index.php?id=foo" to "/foo"#
RewriteCond %{THE_REQUEST} /(?:index\.php)?\?id=([^\s&]+)\sHTTP [NC]
RewriteRule ^ /%1? [L,R]
#2)The rule bellow will internally map "/foo" to "/index.php?id=foo"#
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^([^/]+)/?$ /index.php?id=$1 [L]

现在如何添加自定义参数名称,如 id2(或更多)?

例如

www.example.com/index.php?id=abc --> www.example.com/abc

www.example.com/index.php?id=abc&id2=qaz --> www.example.com/abc/qaz

但是(这里)对此没有改变:

www.example.com/index.php?id=abc&id2=qaz&id3=wsx --> www.example.com/index.php?id=abc&id2=qaz&id3=wsx 

【问题讨论】:

    标签: .htaccess url redirect mod-rewrite url-rewriting


    【解决方案1】:

    您需要另外一组规则来处理 2 个查询参数:

    RewriteEngine On
    
    #1A) Redirect "/index.php?id=foo" to "/foo"
    RewriteCond %{THE_REQUEST} /(?:index\.php)?\?id=([^\s&]+)\sHTTP [NC]
    RewriteRule ^ /%1? [L,R]
    
    #1B) Redirect "/index.php?id=foo&id2=bar" to "/foo/bar"
    RewriteCond %{THE_REQUEST} /(?:index\.php)?\?id=([^\s&]+)&id2=([^\s&]+)\sHTTP [NC]
    RewriteRule ^ /%1/%2? [L,R]
    
    # skip all the files and directories from further rules
    RewriteCond %{REQUEST_FILENAME} -d [OR]
    RewriteCond %{REQUEST_FILENAME} -f
    RewriteRule ^ - [L]
    
    #2A) The rule bellow will internally map "/foo/bar" to "/index.php?id=foo&id2=bar"
    RewriteRule ^([^/]+)/([^/]+)/?$ /index.php?id=$1&id2=$2 [L,QSA]
    
    #2B) The rule bellow will internally map "/foo" to "/index.php?id=foo"
    RewriteRule ^([^/]+)/?$ /index.php?id=$1 [L,QSA]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-05-24
      • 2012-11-07
      • 2014-10-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-03-12
      相关资源
      最近更新 更多