htAccess 将多查询字符串重写为路径



我将如何更改查询字符串

file.php?id=number&string=some-words

进入这个

file/number/some-words/

我知道这之前已经被问过一百万次了,但我在这里看过许多解决方案,它们都是基于单个查询的(就像"某事"而不是"某物"一样(。

同样一旦重写,当使用 $_GET 或 $_REQUEST 等时,php 是否仍然读取原始页面查询字符串......即使它现在显示为路径?

任何帮助,不胜感激。

谢谢。

RewriteRule采用一个正则表达式,该表达式可以像您想要的那样复杂,后跟将加载文件的真实URL。您可以在正则表达式中要捕获的部分周围加上括号,并且可以在 URL 部分中引用第一组的$1,第二组的$2等引用这些部分。例如:

RewriteRule ^(w+)/(d+)/(.*)$ index.php?file=$1&id=$2&words=$3

这将匹配 3 组:

  1. 字母/数字(第一个斜杠以内
  2. (
  3. 一些数字直到第二个斜杠
  4. 之后的任何内容,包括其他斜杠

这些可以通过$1$2$3引用,如第二部分的index.php所示。

唯一的问题是,如果您缺少任何一个部分,则规则中的模式将不匹配。因此,您需要为每个变体制定单独的规则:

#matches all 3 parts
RewriteRule ^(w+)/(d+)/(.*)$ index.php?file=$1&id=$2&words=$3
#matches the first 2 parts
RewriteRule ^(w+)/(d+)$ index.php?file=$1&id=$2
#matches just the first part
RewriteRule ^(w+)$ index.php?file=$1
#matches everything else
RewriteRule ^.*$ index.php

或者你可以做通常所说的bootstrapping,即使用单个RewriteRule将所有内容重定向到单个 php 文件,如下所示:

RewriteRule ^(.*)$ index.php

然后你可以使用 php 来确定不同的部分是什么。在php内部有一个内置的服务器变量$_SERVER['REQUEST_URI'],它将为您提供url的URI部分,该部分是域和第一个斜杠之后的所有内容,包括任何查询字符串参数。这是基于用户请求的URL,而不是由apache重写的URL。您可以explode('/', $_SERVER['REQUEST_URI'])获取单个零件并对其进行任何操作。

您可以将代码放在 Apache .htaccess 文件中。这可能看起来像这样:

Options +FollowSymLinks
RewriteEngine On
RewriteCond %{SCRIPT_FILENAME} !-d
RewriteCond %{SCRIPT_FILENAME} !-f
RewriteRule ^users/(d+)*$ ./profile.php?id=$1
RewriteRule ^threads/(d+)*$ ./thread.php?id=$1
RewriteRule ^search/(.*)$ ./search.php?query=$1

或者你可以只使用 htaccess 和 php:

htaccess

Options +FollowSymLinks
RewriteEngine On
RewriteCond %{SCRIPT_FILENAME} !-d
RewriteCond %{SCRIPT_FILENAME} !-f
RewriteRule ^.*$ ./index.php

.PHP

<?php
#remove the directory path we don't want
$request  = str_replace("/envato/pretty/php/", "", $_SERVER['REQUEST_URI']);
#split the path by '/'
$params     = split("/", $request);
?>

它仍将读取原始页面查询字符串。

最新更新