Score:1

How do you redirect URLs with a query string with htaccess?

er flag

I want to redirect pages like :

example.com/fr/opportunites/?sector_cat=bourses-detudes&ajax_filter=true

To


example.com/fr/bourses-detudes/

the second page is a post type page created with WordPress

Is there any possibility to do that with htacees in litespeed server ?

Thanks a lot

Score:0
kz flag

In order to match against the query string part of the URL you need to use mod_rewrite with a condition (RewriteCond directive) that specifically checks the query string. Other directives only check against the URL-path (which naturally excludes the query string).

So, from your example, to redirect from /fr/opportunites/?sector_cat=<value>&ajax_filter=true to /fr/<value>/ you would need to use something like the following at the top of your .htaccess file before the existing WordPress directives.

RewriteCond %{QUERY_STRING} ^sector_cat=([^&]+)&ajax_filter=true$
RewriteRule ^fr/opportunites/$ /fr/%1/ [QSD,R=302,L]

The URL parameters (sector_cat and ajax_filter) must match in the order stated and no other URL params are permitted. The value of the sector_cat parameter must also be non-empty, otherwise it matches any characters except for &.

The %1 backreference in the RewriteRule substitution contains the captured subpattern from the query string (ie. the sector_cat parameter value).

The QSD (Query String Discard) flag is necessary in order to remove the original query string from the redirected response.

There is no slash prefix on the RewriteRule pattern when used in .htaccess. So, ^fr/ matches /fr/ at the start of the URL-path.

Test first with a 302 (temporary) redirect to avoid potential caching issues and only change to a 301 (permanent) redirect (if that is the intention) once you have confirmed it works as intended.

mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.