I am trying to use URL rewriting to rewrite




and I did

RewriteRule ^search-([a-zA-Z]{2})\.php\?q\=([a-zA-Z0-9_-]*)$ pages-afficher-recherche.php?lang_abbreviation=$1&q=$2 [L]

But I get 404 not found error.

How to keep the question mark in URL rewriting with a GET method?

  • Wouldn't it be easier to have the PHP coffee assume a default value for that parameter? Apr 6, 2018 at 18:23
  • @StephenOstermiller Please can you show me how to do it ?
    – John Max
    Apr 6, 2018 at 18:39
  • 1
    It seems that in order to use question marks in htaccess, you're generally supposed to use QUERY_STRING in you're RewriteRules. I don't use ? parameters so that's all I know.
    – Michael d
    Apr 6, 2018 at 19:40

1 Answer 1

RewriteRule ^search-([a-zA-Z]{2})\.php\?q\=([a-zA-Z0-9_-]*)$ pages-afficher-recherche.php?lang_abbreviation=$1&q=$2 [L]

In order to check the query string part of the URL, you'll need to reference the QUERY_STRING server variable, as @Micheald suggested in comments. However, you need to use a condition (ie. RewriteCond directive), not the RewriteRule directive, in order to perform this check. The RewriteRule pattern checks against the URL-path only, which notably excludes the query string.

The above RewriteRule (that checks for a literal ? in the URL-path) will never match, so the URL is never rewritten. So, assuming /search-en.php?q=abc doesn't exist, this simply triggers a 404.

However, the substitution can also be simplified, since you don't need to explicitly capture the query string (just check it). You simply want to append the query string that satisfies your condition to the end of the new query string, which is achieved with the QSA flag.

Try something like the following instead:

RewriteCond %{QUERY_STRING} ^q=[\w-]*$
RewriteRule ^search-([a-zA-Z]{2})\.php$ pages-afficher-recherche.php?lang_abbreviation=$1 [QSA,L]

\w is a shorthand character class, which is the same as [a-zA-Z0-9_]. The QSA (Query String Append) flag on the RewriteRule will copy the query string from the request (eg. q=abc) and append it to (and merge it with) the query string you have specified on the RewriteRule substitution.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.