问题原文
原帖链接 · John Max · CC BY-SA 3.0
I am trying to use URL rewriting to rewrite
search-en.php?q=abc
to
pages-afficher-recherche.php?lang_abbreviation=en&q=abc
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?
已采纳解答
原帖链接 · MrWhite · CC BY-SA 3.0
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.
摘自公开归档,保留原文语言,版式经整理,外部媒体与邮箱地址已移除。
