skip to Main Content

I need to rewrite a URL with a query string into another URL.

For example, I have https://www.something.com/cat/man/clothing/?colourfilter=blue_red

It needs to be rewritten to https://www.something.com/cat/man/clothing.html/colourfilter=blue_red

I tried to follow the tutorial at https://simonecarletti.com/blog/2009/01/apache-query-string-redirects/

My current attempt is below:

RewriteCond %{QUERY_STRING} ^colourfilter=([a-zA-Z][0-9]-*)$
RewriteRule ^(.)$ (.*).html/colourfilter=%1 [R302,L]

I cannot get it to work.

2

Answers


  1. Your RewriteCond won’t match on the correct query string, your regex now says it should match on any string starting with a letter a-z or A-Z, then a number, then possibly multiple times ‘-‘. If you use https://regex101.com/ , you will notice that for example colourfilter=a9------ matches your regex, which is not correct. You can use ^colourfilter=([a-zA-Z0-9]*_[a-zA-Z0-9]*)$ as regex, that should match your example and fulfill your needs, with this regex any query string starting with a couple of numbers/letters then an underscore and then again some numbers or letters will match.

    Login or Signup to reply.
  2. You may try:

    (.*)/?(.*)
    

    Explanation of the above regex:

    (.*) – Represents first capturing group capturing the part of url before a query string leaving ?.

    /?(.*) – Represents a second capturing group capturing the query string part leaving the ?.

    $1.html/$2$1 represents the first captured group and $2 the second captured group. If $ doesn’t work try replacing with \. This will provide the necessary replacement.

    pictorial representation

    You can find the demo of the above regex in here.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search