WordPress redirect homepage with query string to homepage without query string

We are using WordPress and what I would like to do is to redirect any requests to our main blog page that feature a query string, to the main blog page without a query string. The only exception being a search query.

Therefore:

Read More

/blog/?gibberish should redirect to /blog/

/blog/?gibberish=gibberish should redirect to /blog/

/blog/?s=cats should be processed as normal and not redirect

For simplicity here is the default WordPress redirect rules

# BEGIN WordPress
RewriteRule ^index.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /blog/index.php [L]
# END WordPress

Here is what I have tried so far

# BEGIN WordPress
RewriteRule ^index.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /blog/index.php [L]
RewriteCond %{QUERY_STRING} .
RewriteRule ^$ http://domain.com/ [R=301,L]
# END WordPress

However this comes up with an error in the browser saying the page isn’t redirecting properly.

The reason we want to do this is because we’re using a caching plugin, but it doesn’t cache requests with a query string. At the moment we have lots of malicious requests using nonsense query strings which is bypassing the caching and causing a load on the server.

Related posts

1 comment

  1. You could do this in functions.php as well, executing a function on init to check for bad queries and redirecting as needed.

    add_action('init', 'redirectQuery', 0);
    function redirectQuery(){
        if( isset($_GET['gibberish']) == true ){
                wp_redirect(home_url(), 301);
                die();
        }
    }
    

Comments are closed.