php - =$1 在 url 重写中是什么意思?

标签 php .htaccess mod-rewrite

我无法在 stackoverflow 或 google 上找到有关 =$1 含义的任何信息。我得到了肤浅的信息,但对像我这样的初学者来说一无所获。它有什么作用?

如果我有这样的东西:

www.website.com/profile.php?simon

名字 simon 是否对应于 $1 变量以及为什么是 1

我是这样理解的:

  • (.*) profile/profile.php?id=$1

粗体对应:

  • www.website.com/profile.php?id=simon

重写后变成:

  • www.website.com/profile/simon

我是不是漏掉了什么?

编辑:

RewriteEngine On
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteCond %{REQUEST_FILENAME}.php -d
RewriteRule ^(.*)$ /profile/index.php?id=$1

这个有变化吗

localhost/test/index.php?philip 到: 本地主机/测试/配置文件/菲利普

我尝试输入网址,但失败了。我了解正则表达式的作用,但不知何故我完全混淆了替换的工作原理。

最佳答案

反向引用:

RewriteRule ^.*$ /?id=$1

$1 为空

RewriteRule ^(.*)$ /?id=$1

$1 将是 .* 匹配的任何内容

RewriteRule ^(a|b|c)/(d|e|f)$ /?id=$1-$2

$1 将是“a”、“b”或“c”,具体取决于哪个匹配,$2 将是“d”、“e”或“f”,具体取决于哪一个匹配。

参见:http://httpd.apache.org/docs/trunk/rewrite/intro.html#regex

One important thing here has to be remembered: Whenever you use parentheses in Pattern or in one of the CondPattern, back-references are internally created which can be used with the strings $N and %N (see below). These are available for creating the Substitution parameter of a RewriteRule or the TestString parameter of a RewriteCond.

Captures in the RewriteRule patterns are (counterintuitively) available to all preceding RewriteCond directives, because the RewriteRule expression is evaluated before the individual conditions.

Figure 1 shows to which locations the back-references are transferred for expansion as well as illustrating the flow of the RewriteRule, RewriteCond matching. In the next chapters, we will be exploring how to use these back-references, so do not fret if it seems a bit alien to you at first.

enter image description here


Does this change

localhost/test/index.php?philip to: localhost/test/profile/philip

不,它将 localhost/test/profile/philip 更改为 localhost/profile/index.php?id=philip。假设该规则位于您的“配置文件”目录中的 htaccess 文件中,则:

  1. 浏览器输入或点击链接:localhost/test/profile/philip
  2. 请求发送到本地主机:/test/profile/philip
  3. 请求通过 apache 的处理管道并对其应用 mod_rewrite,请求被截断为 philip
  4. 假设 philip 既不是目录也不是文件,规则将 (.*) 匹配到它,并捕获字符串 philip
  5. 然后规则将请求重写/profile/index.php?id=philip

关于php - =$1 在 url 重写中是什么意思?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32382466/

相关文章:

php - 使用 htaccess 强制重写 url 以提供 css 的绝对路径

php - 了解 woocommerce 主题 - 使用我自己的主题

PHP MySQL 用户最近 10 分钟在线

linux - .htaccess 301 重定向页面,没有扩展到 PHP 页面

.htaccess - 使用 htaccess 删除 URL 末尾的单词

mod-rewrite - phpinfo() mod_rewrite

php - symfony twig 数组按键显示

php - GROUP BY 和 ORDER BY 太慢了。如何使速度更快?

php - Apache 重写 : file not found

php - mod_rewrite规则