Examples

How to redirect all requests with ?id= to index.php in htaccess

Recently one of my sites was hacked and the virus loaded its pages with a redirect to some product on another site. There were more than 5 thousand such pages. Google indexed them. And when I removed the virus, errors appeared in the search console:

search console errors

Most of the URLs looked like this site/?id=numbers

The main error was that such a URL had its own canonical, although the same page was shown.

Perhaps this led to some error and the site stopped being indexed with new articles. I decided to write a rule in xtacess that would redirect such URLs to the main page of the site.

Unfortunately, I did not find a ready-made solution on the Internet, after digging for an hour in the trash of forums, I decided to act on my own and wrote the following rule, which solved the problem:



RewriteEngine On
 # Redirect requests with ?id= to index.php
 RewriteCond %{QUERY_STRING} id=([0-9]+) 
RewriteRule ^(.*)$ index.php? [R=301,L]

Explanation:

RewriteEngine On: This line enables the rewrite engine, which is necessary for any URL rewriting.

RewriteCond %{QUERY_STRING} id=([0-9]+): This condition checks if the query string contains id= followed by one or more digits. The ([0-9]+) part captures the numeric value so it can be used later if needed.

RewriteRule ^(.*)$ index.php? [R=301,L]: This rule redirects any URL that matches the condition to index.php. The ? at the end of the target URL removes any query string from the original request. The [R=301,L] flags indicate that this is a permanent redirect (R=301) and that this should be the last rule to be applied (L).

This setup ensures that any URL with a query string containing id= followed by a numeric value will be redirected to index.php without any query string.