【问题标题】:RewriteRule overrules second rule and GETs index.php?RewriteRule 否决第二条规则并获取 index.php?
【发布时间】:2013-06-18 20:21:52
【问题描述】:

我有一个我认为有效的 RewriteRule:

RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)/(.*)$ index.php?lang=$1&page=$2
RewriteRule ^(.*)/editor/(.*)$ index.php?lang=$1&page=editor&func=$2

当我在第一级(仅限语言和页面)上执行$_GET['lang'] 时,它会返回语言。但如果我在第二层(语言、页面和函数)上尝试它,我会得到index.php

我做错了什么?谢谢!

【问题讨论】:

  • 什么是一级,什么是二级?请注意,第一个重写规则始终为真。 .是“任何字符”的外配符,包括“/”
  • @Pinoniq 第一个重写规则。级别可能是一个令人困惑的东西。

标签: php .htaccess mod-rewrite


【解决方案1】:

您没有[L] 标志在第一次匹配后停止处理,您的第二条规则也将与第一个匹配。因为它更具体,所以先列出它,并包括[L]。此外,我推荐 ([^/]+) 而不是贪婪的 (.*) 来匹配下一个 / 的所有内容:

RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
# List this first, with [L]
RewriteRule ^([^/]+)/editor/(.*)$ index.php?lang=$1&page=editor&func=$2 [L]
# Then URIs not containing editor/ will match the other rule
RewriteRule ^([^/]+)/(.*)$ index.php?lang=$1&page=$2 [L]

如果 CSS 和图像失败,您可能需要将 RewriteCond 移动到 editor/ 规则下方,以确保条件仅适用于最不具体、包罗万象的匹配:

RewriteRule ^([^/]+)/editor/(.*)$ index.php?lang=$1&page=editor&func=$2 [L]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([^/]+)/(.*)$ index.php?lang=$1&page=$2 [L]

【讨论】:

  • 是的!这给了我正确的语言!只有我的样式表和图像不起作用。我的 HTML 中有一个基础。我该如何解决这个问题?
  • @JayWit HTML 中的基础是什么意思? <base href=''> 标签?添加 [L,R] 标志并尝试直接请求您的 CSS 文件之一以查看它被重写到的位置。 RewriteCond 应该照顾好那个...
  • 您可能需要在RewriteRules 之前插入一个中断规则,如stackoverflow.com/questions/1715765/… 中所示
  • 我被重定向到index.php?lang=nl&page=home。图像和 CSS 不能在两个页面上工作。提供的新解决方案也不起作用:[
  • 但是page=home 是从哪里来的呢?你还有其他写信给home的规则吗?
猜你喜欢
  • 1970-01-01
  • 2022-01-03
  • 1970-01-01
  • 1970-01-01
  • 2011-08-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多