htaccess 如何在 URL 重写后访问/获取搜索参数

mcv*_*mcv 5 html php forms .htaccess

我有一个基于提交的表单的 htaccess 重写规则。我正在尝试读取搜索参数,这是关键字搜索的一个简单示例,但理想情况下最终会添加更多参数:

单参数网址: //thesite.com/search?keyword=sample+text

2 参数网址: //thesite.com/search?keyword=sample+text&location=myCity

在我的 htacess 中,我有一个简单的重写规则来寻找这样的搜索:

RewriteRule ^.*search?(.*)$ /displayPage.php?page=search&options=$1
Run Code Online (Sandbox Code Playgroud)

我像这样访问选项参数:

$searchOptions = filter_input(INPUT_GET, "options")!==NULL?filter_input(INPUT_GET, "options"):'';
Run Code Online (Sandbox Code Playgroud)

当我输出这个变量时,它什么都没有。

我试过var_dump($_GET)了,结果是:

array (size=2)
  'page' => string 'search' (length=6)
  'options' => string '' (length=0)
Run Code Online (Sandbox Code Playgroud)

用于生成 url 的 html:

<form class="start-search" action="/search" method="get">
  <input id='keyword' name='keyword' class="search-str" type="text" value="" placeholder="Start Your Search">
  <!-- Meant to hold value for category -->
  <input class="search-cat" type="hidden" value="" placeholder="Start Your Search">

  <button class="btn" type="submit">
    <i class="fa fa-arrow-circle-o-right"></i>
  </button>
</form>
Run Code Online (Sandbox Code Playgroud)

我期待 $searchOptions 包含以下内容:

对于单个参数: keyword=sample+text

对于多个参数: keyword=sample+text&location=myCity

我可以根据 & 和 = 拆分字符串,然后用空格替换 +。

为什么不包括参数的任何想法?

非常感谢你

更新:应用案例 1

RewriteCond %{QUERY_STRING} ^(.*)$
RewriteRule ^search?(.*)/$ displayPage.php?page=search&%1
Run Code Online (Sandbox Code Playgroud)

我的 apache 日志报告以下内容:

"GET /search?keyword=test+text HTTP/1.1" 404 286
Run Code Online (Sandbox Code Playgroud)

什么是不正确的?我尝试删除 ? 根据重写规则,我将其替换为 / 作为提供的示例。我修改了 html 以在它之后包含一个 / 。当我执行以下操作时,apache 日志中报告了以下内容:

"GET /search/?keyword=test+text HTTP/1.1" 301 329
"GET /search?keyword=test+text HTTP/1.1" 404 286
Run Code Online (Sandbox Code Playgroud)

其他 HTACCESS 信息

我已经申请了以下内容

RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)/$ /$1 [L,R=301]
Run Code Online (Sandbox Code Playgroud)

我有一堆其他的 RewriteRule 用于其他所有功能的 url。这是我难倒的第一个查询字符串。

更新2

尝试史蒂夫 E. [QSA]

RewriteRule ^.*search?(.*)/$ displayPage.php?page=search&%1 [QSA]
Run Code Online (Sandbox Code Playgroud)

Apache 日志报告

 "GET /search?keyword=sample+search HTTP/1.1" 404 286
Run Code Online (Sandbox Code Playgroud)

解决方案:正如 Steve E 提供的那样,上面有一个修复程序,在调用 displayPage.php 之前忘记了 /。它适用于单个和多个参数。:)

RewriteRule ^.*search?(.*)/$ /displayPage.php?page=search&%1 [QSA]
Run Code Online (Sandbox Code Playgroud)

Ste*_* E. 4

在 RewriteRule 上使用 [QSA] 标志

RewriteRule ^search?(.*)/$ displayPage.php?page=search&%1 [QSA]
Run Code Online (Sandbox Code Playgroud)

这是文档

修改查询字符串 默认情况下,查询字符串不加修改地传递。但是,您可以在包含查询字符串部分的替换字符串中创建 URL。只需在替换字符串中使用问号即可指示以下文本应重新插入查询字符串中。当您想要删除现有查询字符串时,只需用问号结束替换字符串。要组合新旧查询字符串,请使用 [QSA] 标志。