【问题标题】:Regex match for the whole custom querystring整个自定义查询字符串的正则表达式匹配
【发布时间】:2014-03-30 05:02:01
【问题描述】:

我的 Web 应用程序的 URL 采用以下形式:

/cms/welcome
/cms/system-admin/groups
/cms/system-admin/standard-lists/accounting/COA
....
....

我正在尝试找到一个正则表达式,将其翻译为:

/cms/index.php?content=welcome
/cms/index.php?content=system-admin/groups
/cms/index.php?content=system-admin/standard-lists/accounting/COA
....
....

我在下面尝试了这个,但它没有给出“在此服务器上找不到请求的 URL /cms/welcome/”,'请求的 URL /cms/system-admin/在此服务器等上找不到组

RewriteEngine On
RewriteBase /cms
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^([^/]+)/?$ index.php?content=$1 [L]

我的假设是:^([^/]+)/?$ 应该匹配 /cms/ 之后的任何内容并将其存储在 $1强>。 任何帮助将不胜感激。 以下重写规则也失败了: RewriteRule ^(.*)$ index.php?page=$1

重写规则 ^/?([A-Za-z0-9-/]+)/?$ index.php?page=$1 [QSA,L]

【问题讨论】:

  • 第一个问题很好。你花时间标记它,展示你尝试过的东西说出你的想法和假设。一个小点:你所有的网址都以,结尾吗?是否应该重写为以;结尾?

标签: regex .htaccess mod-rewrite


【解决方案1】:
# Turn on rewriting
RewriteEngine On
# Starting with /cms
RewriteBase /cms
# If there's no file that matches the request
RewriteCond %{REQUEST_FILENAME} !-f
# *nor* a directory
RewriteCond %{REQUEST_FILENAME} !-d
# Then rewrite retaining any parameters [QSA] and stop [L]
RewriteRule ^(.*)$ index.php?content=$1 [L,QSA]

你能发现你做错了什么吗?

检查 RewriteCond 指令

需要其他提示吗?

您的第二个 RewriteCond 说:仅当请求的文件系统目录确实存在时才重写;有个 '!'不见了。

【讨论】:

  • Chris 没有考虑逗号和分号,正如我在第一个示例中清楚显示的那样。所以我尝试了这个 rawriterule: RawriteRule ^(.*)$ index.php?content=$1 [L,QSA] 但它仍然失败。
  • 我已经调整了问题和答案以反映这一点。您不应该只更改 RewriteRule,而是更改所有 Rewrite... 指令。
  • 别忘了重新加载你的 apache。
  • 感谢克里斯的快速通知。现在我刚刚将您的答案复制到位于 cms 文件夹中的 .htaccess 文件中,现在我得到“页面未正确重定向。Firefox 检测到服务器正在以某种方式重定向对该地址的请求永远不会完成。” - 可能是无限循环。谢谢。
  • @JamesMwaiponya 这个 RewriteRule 应该在服务器内部。您提到的错误听起来像是转到浏览器的 HTTP 3xx 重定向。您是否有任何重定向规则(带有[R] 标志的 RewriteRule 或重定向指令)?这可能在 .htaccess、 或服务器配置中。
【解决方案2】:

这是正则表达式:

(/cms/)(.*)

并将其替换为:

$1index.php?content=$2

我对php或htaccess一无所知,但我认为这应该可行:

RewriteEngine On
RewriteBase /cms
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule (/cms/)(.*) $1index.php?content=$2 [L]

【讨论】:

  • 嗨阿米特·乔基! RewriteRule (/cms/)(.*)index.php?content=$1 [L] 不起作用。仍然给出错误 404
  • @JamesMwaiponya,/cms 之前有什么东西吗?
  • 是的,localhost:8888 或者如果您正在寻找文件夹层次结构,它是 c:\inetpubapache\wwwroot\。谢谢。
  • 立即查看我的答案
  • 我刚刚复制了新的重写规则:RewriteRule (.*)(/cms/)(.*) $1$2index.php?content=$3 [L] 但它仍然给出错误 404跨度>
猜你喜欢
  • 1970-01-01
  • 2020-09-19
  • 1970-01-01
  • 1970-01-01
  • 2017-09-26
  • 1970-01-01
  • 2019-04-24
  • 1970-01-01
相关资源
最近更新 更多