【问题标题】:How to make .htaccess RewriteRule that support path and query_string at the same time如何制作同时支持路径和查询字符串的.htaccess RewriteRule
【发布时间】:2022-11-24 17:29:19
【问题描述】:

我需要关于 RewriteRule 的 .htaccess 方面的帮助。我已经有一些使用 RewriteRule 的 URL,例如:

https://example.com/content/2/about_us

上面的这个 URL,我可以成功重定向到 page.php 并捕获像 id=2 和 pagename=about_us 这样的变量

但是有一些 URL 我想同时拥有关于格式和普通 query_string 的格式,如下所示:

https://example.com/page?keyword=battery&sort=asc&pagenum=1

上面的这个 URL 将重定向到 page.php,我想捕获 query_string。这些query_string 不限于关键字、排序、页码。它可以是任何其他名称。目前我根本无法捕获 query_string。

目前我只能使用以下内容将 URL https://example.com/page 重定向到 page.php: RewriteRule ^page/?$ page.php [L]

任何人都可以帮忙吗?

【问题讨论】:

  • 您能否确认您在浏览器中点击的链接以及您希望它成为什么链接?谢谢你。
  • @RavinderSingh13 这是浏览器example.com/page?keyword=battery&sort=asc&pagenum=1 中的链接。它不需要重写为任何其他格式,只是我需要能够在后面提取 query_string。
  • @RavinderSingh13 在我的示例中,我想要实现的是两种类型的组合。正常重写这个 example.com/content/2/about_us 加上额外的 query_string 可以是 example.com/content/2/about_us?tag=battery&sort=asc
  • 现有的查询字符串应该自动附加,直到你明确地做了任何反对它的事情。也许您配置了更多的重写,这会以某种方式干扰它?如果是这样,请向我们展示完整的东西。

标签: .htaccess redirect mod-rewrite


【解决方案1】:

使用您显示的示例和尝试,请尝试遵循 .htaccess 规则文件。

请确保:

  • 将您的 .htaccess 规则文件与 content 文件夹放在一起。
  • 在测试您的 URL 之前清除您的浏览器缓存。
RewriteEngine ON

RewriteBase /content/2/

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(content/2)/([^/]*)/?$ $1/$2.php?tag=battery&sort=asc [NC,QSA,L]

【讨论】:

  • 根据最后一行,如果我将 (content/2)/(about_us) 放在里面,那么它将是一个静态 url。事实上,URL 可以是 example.com/content/2/about_us 或 .../content/14/list 等等。所以 URL 非常动态,如下所示:example.com/content/<dynamic_id>/…>
  • @EdisonWong,好的,我已经编辑了我的规则一次,让我知道进展如何,干杯。
  • @EdisonWong,请确保在测试您的 URL 之前清除您的浏览器缓存。
猜你喜欢
  • 2019-01-02
  • 2016-03-26
  • 1970-01-01
  • 2013-06-29
  • 2011-03-07
  • 1970-01-01
  • 2021-06-13
  • 2018-07-25
  • 2022-01-18
相关资源
最近更新 更多