Nick
Nick

Reputation: 53

Using htaccess to redirect anything after a parameter - regex

Id like to have the following URL(s) redirect to the same URL just without the ?

For example:

https://www.example.com/this-is-static?numbersletterssymbols

goes to

https://www.example.com/this-is-static

"numbersletterssymbols" can be anything

Id like this to be a 301 , using htaccess ( apache )

I came across the following, however, the variable seems to be in parentheses

RewriteCond %{QUERY_STRING} ^product=(.*)$
RewriteRule ^test.php$ %1/? [R=301,L]

Any insight is appreciated

Upvotes: 1

Views: 428

Answers (1)

MrWhite
MrWhite

Reputation: 45829

To remove the query string (any query string) from any URL you could do the following using mod_rewrite, near the top of your .htaccess file:

RewriteEngine On

RewriteCond %{QUERY_STRING} .
RewriteRule ^ %{REQUEST_URI} [QSD,R=301,L]

The condition (RewriteCond directive) simply asserts that there is a query string consisting of at least 1 character (determined by the regex . - a single dot).

The QSD (Query String Discard) flag removes the original query string from the redirected response. The QSD flag requires Apache 2.4 (which you are most probably using). The method used on earlier versions of Apache, as in your example, is to append a ? to the susbstitution string (essentially an empty query string).

Note that you should test first with a 302 (temporary) redirect to avoid potential caching issues.


however, the variable seems to be in parentheses

The parentheses in the regex simply creates a "capturing group" which can be referenced later with a backreference. eg. In your example, the value of the product URL parameter is referenced in the RewriteRule substitution string using the %1 backreference in order to redirect to the value of the URL parameter. This is very different to what you are trying to do and is arguably a security issue. eg. It would redirect a request for /test.php?product=https://malicious.com to https://malicious.com/, allowing a potential hacker to relay traffic via your site.


UPDATE: is it possible to make this work only for when the URL begins with "this-is-static" (for example)

Yes, the RewriteRule pattern (1st argument) matches the URL-path, less the slash prefix. For example:

RewriteCond %{QUERY_STRING} .
RewriteRule ^this-is-static %{REQUEST_URI} [QSD,R=301,L]

Matches all URLs that start with /this-is-static.

Upvotes: 3

Related Questions