Search code examples
apache.htaccesshttp-redirectmod-rewrite

Redirect with dynamic parameters .htaccess


There is a dynamic parameter in urls s=changingtext. It is necessary to recognize this parameter and add another parameter to it for redirecting to get s=changingtext&post_type=product.

There is a link for example

example.com/?min_price=0&max_price=0&s=test

it should always redirect to

example.com/?min_price=0&max_price=0&s=test&post_type=product

Solution

  • Providing the order of the URL parameters is not significant then you can do it like this using mod_rewrite at the top of your .htaccess file:

    RewriteEngine On
    
    RewriteCond %{QUERY_STRING} (^|&)s=[^&]+
    RewriteRule ^ %{REQUEST_URI}?post_type=product [QSA,R=302,L]
    

    This adds the post_type URL parameter first and the existing query string is appended using the QSA (Query String Append) flag. ie. In your example, it will be redirected to example.com/?post_type=product&min_price=0&max_price=0&s=test.

    This specifically checks for a non-empty s URL parameter. An empty URL parameter, eg. foo=1&s=&bar=1 will not be redirected.

    This applies to any URL-path.