'Redirect exactly null query string

I have a lot of websites on my web server.

I just want to redirect all my websites when the url is exactly /?

For example:

  • www.example1.com/?
  • www.example2.com/?

but not like www.example.com/x.php?, www.example.com/ or anything else.

I've tried many things but failed:

RewriteCond %{QUERY_STRING} ^$
RewriteRule ^ %{REQUEST_URI}?_test [L,R=302]

RewriteCond %{QUERY_STRING} ^\?$
RewriteRule  ^ http://www.example.com [L,R=301]

RewriteCond %{REQUEST_URI} =="/?"
RewriteRule ^(.*)$ http://www.example.com/ [L,R=301]


Solution 1:[1]

To redirect an empty query string (ie. when the URL simply ends with a ?), you need to check against THE_REQUEST.

The RewriteRule pattern matches against the URL-path, which notably excludes the query string (including the ?).

The REQUEST_URI server variable also omits the query string and any trailing ?. (Note that this is different to the $_SERVER['REQUEST_URI'] variable in PHP, which does include the full request URL.)

And the QUERY_STRING variable is empty regardless of whether a trailing ? is present or not.

So, in order to remove (ie. redirect) a trailing ? from the end of the URL, you can do something like the following:

RewriteCond %{THE_REQUEST} ^[A-Z]{3,9}\ (.+)\?\ HTTP/
RewriteRule ^ %1? [R,L]

The trailing ? on the end of the RewriteRule substitution (%1?) is not actually present in the resulting URL, but is required in order to remove the query string entirely. Alternatively, if you are on Apache 2.4+ you can use the QSD (Query string Discard) flag instead:

RewriteRule ^ %1 [R,L,QSD]

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 MrWhite