Ad

How To Delete All ?source Line Code In URL With Rewrite Rule For The 301 Redirect

- 1 answer

Please help me to write the correct RewriteRule for the 301 redirect (.htaccess under subdomain blog.example.com) for the links like:

from

https://blog.example.com/?source=tag_archive---------0-----------

redirect to

https://example.com/blog/

I use these lines in .htaccess:

RewriteEngine on
RewriteCond %{HTTP_HOST}  ^blog\.example\.com$ [NC]
RewriteCond %{QUERY_STRING}  ^source=tag_archive---------0-----------(&.*)?$ [NC]
RewriteRule ^(.*)$ https://example.com/blog/  [R=301,NE,NC,L]

With the example above I got

https://example.com/blog/?source=tag_archive---------0-----------

but need

https://example.com/blog/

(without part ?source=tag_archive---------0-----------)

Ad

Answer

On Apache 2.4+ you need to add the QSD (Query String Discard) flag to the RewriteRule directive:

RewriteRule ^ https://domainname.com/blog/  [QSD,R=301,L]

(Alternatively, if you are still on Apache 2.2, then append a ? to the end of the substitution string - effectively an empty query string. The ? itself will not be in the redirect response.)

^(.*)$ (the RewriteRulepattern) - since you are matching any URL-path and not using the backreference, this can be simplified to ^.

The NC and NE flags are not required here.

However, as noted above, this redirects any URL-path. If you specifically want to redirect https://blog.example.com/?source=tag...only then change the RewriteRulepattern to ^$ (an empty URL-path). For example:

RewriteRule ^$ https://domainname.com/blog/  [QSD,R=301,L]
Ad
source: stackoverflow.com
Ad