使用htaccess删除单个查询参数 [英] Using htaccess to remove single query parameter

查看:93
本文介绍了使用htaccess删除单个查询参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

出于不必要的原因,Google一直在使用网址中不必要的查询字符串为我的网站之一建立索引。我想将htaccess文件修改为301,将所有这些请求重定向到URL,而无需查询字符串的不需要部分,但保留查询字符串的任何其他部分,这些部分可能(也可能不是)地址的一部分确保保留了其他功能。

For reasons that aren't worth going into here, Google have been indexing one of my sites with an unnecessary query string in the URL. I'd like to modify my htaccess file to 301 redirect all those requests to the URL without the unneeded part of the query string, but retain any other parts of the query string which may (or may not) be part of the address to make sure other functionality is retained.

例如,以下URL

http://example.com/product.php?query=12345
http://example.com/index.php?section=ABC123&query=56789
http://example.com/search.php?query=987654&term=keyword

将成为

http://example.com/product.php
http://example.com/index.php?section=ABC123
http://example.com/search.php?term=keyword

有效地剥离'query = XXXXX加?或& ;,但确保在删除后仍保留其他查询并使用正确的语法(即,仅从第三个示例中删除?query = 98765不会起作用,因为它将链接保留为search.php& term = keyword而不是search.php?term =关键字)。

Effectively stripping 'query=XXXXX' plus the ? or &, but making sure other queries are retained and in correct syntax after the removal (i.e., just removing ?query=98765 from the third example wouldn't work, as it would leave the link as search.php&term=keyword rather than search.php?term=keyword).

正在查看其他一些Stack的答案,发现了这一点:

Was looking through some other Stack answers and found this:

RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{QUERY_STRING}  (.*)?&?query=[^&]+&?(.*)?  [NC]
RewriteCond %{REQUEST_URI} /(.*)
RewriteRule .*  %3?%1%2? [R=301,L]

但这似乎不起作用,我对htaccess的了解& regex不足以找出原因。

But that doesn't seem to work, and my knowledge of htaccess & regex isn't good enough to figure out why.

预先感谢任何指针。

推荐答案

尝试一下(我用您的示例对其进行了测试,并且工作正常):

Try this (i tested it with your examples and it is working fine):

RewriteEngine on

RewriteCond %{QUERY_STRING} ^(.*)&?query=[^&]+&?(.*)$ [NC]
RewriteRule ^/?(.*)$ /$1?%1%2 [R=301,L]

此外,您还应该添加条件以仅将此规则应用于现有文件(由您自己决定)。

如果您愿意:

Also, you should add a condition to apply this rule only on existing files (that's up to you).
If you want it:

RewriteEngine on

RewriteCond %{REQUEST_FILENAME} -f
RewriteCond %{QUERY_STRING} ^(.*)&?query=[^&]+&?(.*)$ [NC]
RewriteRule ^/?(.*)$ /$1?%1%2 [R=301,L]

这篇关于使用htaccess删除单个查询参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆