PeteSE4
PeteSE4

Reputation: 327

Using htaccess to remove single query parameter

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.

For example, the following URLs

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

Would become

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

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).

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]

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

Thanks in advance for any pointers.

Upvotes: 4

Views: 6534

Answers (2)

Justin Iurman
Justin Iurman

Reputation: 19016

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,NE]

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,NE]

Upvotes: 7

PABLO
PABLO

Reputation: 31

It seems there is a mistake or something. Here is working solution:

RewriteEngine on

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

This code removes just one parameter. Working perfect.

Upvotes: 3

Related Questions