【问题标题】:Using htaccess to force a trailing slash before the ? with a query string?使用 htaccess 在 ?带有查询字符串?
【发布时间】:2012-02-02 17:40:28
【问题描述】:

我的 htaccess 文件中有以下内容:

RewriteEngine On
RewriteBase /

# Check to see if the URL points to a valid file
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d

# Trailing slash check
RewriteCond %{REQUEST_URI} !(.*)/$

# Add slash if missing & redirect
RewriteRule ^(.*)$ $1/ [L,R=301]

# Check to see if the URL points to a valid file
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d

# Send to index.php for clean URLs
RewriteRule ^(.*)$ index.php?/$1 [L]

这确实有效。它隐藏了 index.php,并添加了一个斜杠……除非有查询字符串。

这个网址:

http://example.com/some-page

被重定向到:

http://example.com/some-page/

但是这个网址:

http://example.com/some-page?some-var=foo&some-other-var=bar

不会被重定向。我希望将以上内容发送至:

http://example.com/some-page/?some-var=foo&some-other-var=bar

我已经达到了我对重定向的理解的极限。如果您有一个可行的答案,我将非常感谢每条线路在做什么以及它为什么起作用的演练。解释为什么我现在拥有的在涉及查询字符串时不起作用的双重奖励。

【问题讨论】:

    标签: regex apache .htaccess routes pattern-matching


    【解决方案1】:

    尝试在最后一个重定向规则的末尾添加[QSA] 以保留原始查询字符串,如下所示

    # Send to index.php for clean URLs, preserve original query string
    RewriteRule ^(.*)$ index.php?/$1 [L,QSA]
    

    每条线路的作用及其工作原理的演练。

    在下面查看我的 cmets

    #turn mod_rewrite engine on.
    RewriteEngine On
    #set the base for urls here to /
    RewriteBase /
    
    ### if the is not a request for an existing file or directory
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    
    ### and the URI does not end with a /
    RewriteCond %{REQUEST_URI} !(.*)/$
    
    ### redirect and add the slash. 
    RewriteRule ^(.*)$ $1/ [L,R=301]
    
    ### if the is not a request for an existing file or directory
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    
    # rewrite to index.php passing the URI as a path, QSA will preserve the existing query string
    RewriteRule ^(.*)$ index.php?/$1 [L,QSA]
    

    【讨论】:

    • 我想保留查询字符串,而不是剥离它。你的设置把这个:http://example.com/some-page?test-var=foo 变成了这个:http://example.com/some-page / 我在找这个:http://example。 com/some-page/?test-var=foo
    【解决方案2】:

    我相信如果你改变这个:

    RewriteCond %{REQUEST_URI} !(.*)/$
    RewriteRule ^(.*)$ $1/ [L,R=301]
    

    到这里:

    RewriteCond %{REQUEST_URI} !^([^?]*)/($|\?)
    RewriteRule ^([^?]*) $1/ [L,R=301]
    

    那么它应该做你想做的。

    我所做的更改是:

    • 在重写条件和规则中,我将(.*)^(.*) 更改为^([^?]*),以确保如果有查询字符串,则它不包含在任一正则表达式中。 ([^…] 表示“任何不在 中的字符”,所以[^?] 表示“任何不是问号的字符”。)
    • 在rewrite-condition,我把$改成了($|\?),以便匹配either end-of-URL or end-of-part-在查询字符串之前。
    • 在重写规则中,我删除了 $,因为不再需要它。

    【讨论】:

      猜你喜欢
      • 2013-03-26
      • 1970-01-01
      • 1970-01-01
      • 2020-03-18
      • 2013-12-21
      • 2016-01-18
      • 2014-07-08
      • 1970-01-01
      • 2017-09-14
      相关资源
      最近更新 更多