大网数据广告活动
网站运营与故障问答

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

· 52CE 我爱测

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_a…

问题原文

原帖链接 · 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.

摘自公开归档,保留原文语言,版式经整理,外部媒体与邮箱地址已移除。

资料来源与适用范围

资料来源
Webmasters Stack Exchange
适用范围
以原帖系统、软件版本与发布日期为准(2018-04-06)
内容语言
中文;命令、路径和错误标识保留技术原文
本地收录日期
2026-11-15
授权说明
CC BY-SA 3.0

正文与所需资源由本站本地存储。查看来源及更新记录 ↗

请按适用版本和实际日志确认原因;本站没有对每一种系统或设备逐项执行文中的操作。