使用htaccess删除尾随问号

时间:2013-01-04 21:29:27

标签: .htaccess

有人可以帮我理解这段代码吗?

# Remove trailing ?
RewriteCond %{THE_REQUEST} ? HTTP [NC] 
RewriteRule .? /%{REQUEST_URI}? [R=301,L]

基本上我有一个网站www.example.com正在生成一个指向www.example.com/index.cfm的链接?我需要它重定向到www.example.com以进行SEO复制。我设法删除index.cfm但是?仍然留在那里(www.example.com/?)。如果它是最后一个字符,也会删除尾部斜杠。我在网上找到了这个规则,但是我在apache中收到了一个“RewriteCond:bad flag delimiters”警报,它没有做任何事情。

我也有一些像www.example.com/index.cfm?term=test这样的页面用于搜索,所以我只想摆脱拖尾的问号,而不是在我附加查询时。

错误发生在RewriteCond中。我需要帮助了解情况以及为什么它不起作用而不只是答案。

以防这是整个htaccess:

RewriteEngine On
Rewritebase /

# remove trailing index.cfm
RewriteRule ^index.cfm(\?)?$ / [R=301,L]

# SEF URLs
SetEnv SEF_REQUEST false
RewriteRule ^[a-z\d\-]+/[a-z]\d+/? /index.cfm/$0 [NC,PT,QSA,E=SEF_REQUEST:true]
RequestHeader add SEF-Request %{SEF_REQUEST}e
RewriteCond %{HTTP:SEF_REQUES} ^true$ [NC]
RewriteRule . - [L]

# Remove trailing ?
RewriteCond %{THE_REQUEST} ? HTTP [NC] 
RewriteRule .? ^%{REQUEST_URI}? [R=301,L]

注意:我在发布之前搜索了online / stackoverflow,但没有找到解决问题的方法。

编辑:我还注意到我的RewriteRule ^ index.cfm(\?)?$ / [R = 301,L]正在删除index.cfm,即使它不是url中的最后一个导致404的时候我尝试搜索一些东西(www.example.com/index.cfm?term=test)如果有人可以纠正我,那么探索就会很棒。谢谢你。

EDIT2:www.example.com/index.cfm?term=test&a=dh&j=dhjsi不应重定向。 不应重定向www.example.com/a/b/d/f/h/w/d。 www.example.com/index.cfm?和www.example.com/index.cfm应重定向到www.example.com。

2 个答案:

答案 0 :(得分:4)

RewriteCond %{THE_REQUEST} ? HTTP [NC] 
RewriteRule .? ^%{REQUEST_URI}? [R=301,L]

不能正常工作,因为?是正则表达式的保留字符,您需要将其与空格一起转义。尝试:

RewriteCond %{THE_REQUEST} \?\ HTTP [NC] 
RewriteRule ^/?(index\.cfm)? /? [R=301,L]

此外,您希望此规则位于# remove trailing index.cfm规则下,而不是最底层。

答案 1 :(得分:-1)

1)案例1:删除问号

http://example.com/page/subpage/?YOURSTRING=blabla

重定向到

http://example.com/page/subpage/

然后在.htaccess的开头,插入:

<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{QUERY_STRING} YOURSTRING=(.*)
RewriteRule ^(.*)$ /$1? [R=301,L]
</IfModule>

# if wordpres isnot installed in root folder, then edit the fourth line to this
# RewriteRule ^(.*)$ /YOUR-WORDPRESS-DIRECTORY/$1? [R=301,L]

2)案例2:从问号重定向到另一个链接

http://example.com/index.php?YOURSTRING=blabla&id=44

重定向到

http://example.com/page/subpage/

使用:

<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{QUERY_STRING} YOURSTRING=blabla&id=44
RewriteRule ^(.*)$ http://example.com/page/subpage/? [R=301,L]
</IfModule>
相关问题