Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

301 Redirect for Query String on Root?

I have tried multiple methods of trying to redirect some URLs with a query string on the root, for example, if I try to match the URL http://example.com/?bloginfo=racing

Redirect 301 "/?bloginfo=racing" http://example.com/racing

or

RedirectMatch 301 ^/?bloginfo=racing$ http://example.com/racing

The condition will never match. Is there a good method for this inside of my .htaccess file to write this kind of redirect?

like image 660
Miura-shi Avatar asked Mar 03 '26 10:03

Miura-shi


2 Answers

If you want to match the query string you need to use mod_rewrite and check the QUERY_STRING server variable in a RewriteCond directive. mod_alias directives (ie. Redirect and RedirectMatch match the URL-path only, not the query string).

For example, to redirect http://example.com/?bloginfo=racing to http://example.com/racing you could do something like the following:

RewriteEngine On

RewriteCond %{QUERY_STRING} ^bloginfo=racing$
RewriteRule ^$ /racing? [R=302,L]

The trailing ? on the substitution is required in order to remove the query string from the request, otherwise, it is passed through to the target URL. Alternatively, use the QSD flag on Apache 2.4+

Change the 302 (temporary) to 301 (permanent) if this is intended to be permanent and only when you are sure it's working OK (to avoid caching problems).

To make this more generic and redirect /?bloginfo=<something> to /<something> then you can do something like the following:

RewriteCond %{QUERY_STRING} ^bloginfo=([^&]+)
RewriteRule ^$ /%1? [R=302,L]

%1 is a backreference to the captured subpattern in the last match CondPattern.

like image 176
MrWhite Avatar answered Mar 06 '26 00:03

MrWhite


Query string is separate variable from Request URI, so you will have to do something like this:

RewriteEngine On
RewriteCond %{QUERY_STRING} bloginfo=racing 
RewriteRule ^$ /racing [L,R]
like image 40
Dusan Bajic Avatar answered Mar 06 '26 00:03

Dusan Bajic



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!