Patrick Taylor

htaccess redirect all query strings except (some)

For when pages can be accessed with a query string and you want to prevent (eg):

https://example.com/?key=value (non-existent URL) being accessed

... but you want to allow (eg):

https://example.com/folder1/?key=value (valid URL)
https://example.com/folder2/page?key=value (valid URL)
https://example.com/page?key=value (valid URL)


This seems to work:

<IfModule mod_rewrite.c>
  RewriteEngine on
  RewriteCond %{QUERY_STRING} .
  RewriteCond %{REQUEST_URI} !^/(folder1|folder2|page)
  RewriteRule ^ %{REQUEST_URI} [QSD,R=301,L]
</IfModule>

(1) Specify this applies to all query strings.

(2) Negate certain exceptions as required.

(3) Redirect all other requests with no query string.

However, if the .htaccess file also has 'canonical' redirect rules, for example to redirect 'www' URLs to non-www:

<IfModule mod_rewrite.c>
// Normal canonical redirect
  RewriteCond %{HTTP_HOST} ^www\. [NC]
  RewriteRule (.*) https://example.com/$1 [R=301,L]
</IfModule>

... then the following:

http://example.com/?key=value (redirect) —> https://example.com/

... would have two redirects, so this may be better:

<IfModule mod_rewrite.c>
  RewriteEngine on
// Redirect query string to canonical URL
  RewriteCond %{QUERY_STRING} .
  RewriteCond %{REQUEST_URI} !^/(folder1|folder2|page)
  RewriteRule ^ https://example.com%{REQUEST_URI} [QSD,R=301,L]

// Normal canonical redirect
  RewriteCond %{HTTP_HOST} ^www\. [NC]
  RewriteRule (.*) https://example.com/$1 [R=301,L]
</IfModule>

... which redirects only once. In this instance if the request has both 'www' and a query string, the second 'canonical' redirect is not used.

Technical »

Page last modified: 18 September, 2020