【问题标题】:Rewrite query string parameter into URL Apache将查询字符串参数重写为 URL Apache
【发布时间】:2015-04-27 14:07:45
【问题描述】:

进入 Apache 的 URL:

localhost:8888/game?level=0

应该来自 apache 的 URL:

localhost:8888/level0/game

有人可以帮我创建这个重写吗?

尝试通过以下方式解决:

重写引擎开启
RewriteRule ^game\/+(.*?)\?+level=+([0-9]+) /level$2/$1 [L,QSA]

没有运气,因为它不匹配。

谢谢, 彼得

【问题讨论】:

  • 如果您提供您尝试解决此问题的方法,您将获得更多帮助。
  • @hwnd 添加了我尝试过的解决方案
  • 你确定你想要重写的方向(让静态的东西看起来动态吗?)最常见的重写规则是相反的。无论如何,在 RewriteRule 中,您将能够仅匹配 url 路径(没有查询字符串)。您需要RewriteCond %{QUERY_STRING} ..... 来捕获查询字符串值,请参阅wiki.apache.org/httpd/RewriteQueryString
  • @guido 是的,这是正确的方向。所以,添加 RewriteCond %{QUERY_STRING} 游戏仍然不能解决它.. 你能建议更进一步的方向吗?

标签: regex apache .htaccess query-string


【解决方案1】:

为了能够从查询字符串中捕获值,您需要一个 RewriteCond %{QUERY_STRING} 指令,以便捕获的组将在以下 RewriteRule 中用作 %n 占位符:

RewriteCond %{QUERY_STRING} ^level=(.*)$
RewriteRule ^game /level%1/game [L]

如果你在浏览器中输入/game?level=0,apache会打开/level0/game;无需将查询字符串附加到重写的 url(QSA 标志)

【讨论】:

  • 这似乎不起作用,当我复制粘贴这些设置并打开开始 url 时,我收到 Not Found The requested URL /game was not found on this server.适用于 ^game
  • @Peter 起始网址是什么?
  • 并且在该上下文的文档根目录下是否存在/level0/game 文件?
  • @Peter 抱歉,我错过了您第一条评论的最后 Works with ^game 部分,我打错了
  • @anubhava 是的,他有不寻常的要求,正如你所看到的,我确保在问题下方的评论中提问
【解决方案2】:

您可以在 DOCUMENT_ROOT/.htaccess 文件中使用此代码:

RewriteEngine On
RewriteBase /

# external redirect from actual URL to pretty one
RewriteCond %{THE_REQUEST} /(game)\?(level)=(\d+) [NC]
RewriteRule ^ %2%3/%1? [R=302,L,NE]

# internal forward from pretty URL to actual one
RewriteRule ^(level)(\d+)/([^/.]+)/?$ $3?$1=$2 [L,QSA,NC]

【讨论】:

    猜你喜欢
    • 2019-02-13
    • 2021-01-06
    • 1970-01-01
    • 2011-09-09
    • 2012-10-08
    • 2011-11-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多