你需要一些东西:
-
设置一个 .htaccess 以将所有请求重定向到您的主文件,该文件将处理所有这些,例如:
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>
上面会将所有不存在的文件和文件夹的请求重定向到您的index.php
现在您要处理 URL 路径,以便可以使用 PHP 变量 $_SERVER['REQUEST_URI'],正如您所提到的。
-
从它的解析结果中提取你想要的信息,你可以使用parse_url或pathinfo或explode中的一个函数来做到这一点。
使用parse_url 这可能是最常用的方法:
$s = empty($_SERVER["HTTPS"]) ? '' : ($_SERVER["HTTPS"] == "on") ? "https" : "http";
$url = $s . '://' . $_SERVER["HTTP_HOST"] . $_SERVER["REQUEST_URI"];
var_dump(parse_url($url));
输出:
["scheme"] => string(4) "http"
["host"] => string(10) "domain.com"
["path"] => string(36) "/health/2013/08/25/some-random-title"
["query"] => string(17) "with=query-string"
所以parse_url 可以轻松分解当前 URL,如您所见。
例如使用pathinfo:
$path_parts = pathinfo($_SERVER['REQUEST_URI']);
$path_parts['dirname'] 将返回 /health/2013/08/25/
$path_parts['basename'] 将返回 some-random-title,如果它有扩展名,它将返回 some-random-title.html
$path_parts['extension'] 将返回空,如果它有扩展名,它将返回 .html
$path_parts['filename'] 将返回 some-random-title,如果它有扩展名,它将返回 some-random-title.html
像这样使用爆炸:
$parts = explode('/', $path);
foreach ($parts as $part)
echo $part, "\n";
输出:
health
2013
08
25
some-random-title.php
当然,这些只是您如何阅读它的示例。
您还可以使用 .htaccess 来制定特定规则,而不是从一个文件中处理所有内容,例如:
RewriteRule ^([^/]+)/([0-9]+)/([0-9]+)/([0-9]+)/([^/]+)/?$ blog.php?category=$1&date=$2-$3-$4&title=$5 [L]
基本上,上面会分解 URL 路径并在内部使用适当的参数将其重定向到您的文件 blog.php,因此使用您的 URL 示例它将重定向到:
http://www.mysite.com/blog.php?category=health&date=2013-08-25&title=some-random-title
但是在客户端浏览器上,URL 将保持不变:
http://www.mysite.com/health/2013/08/25/some-random-title
还有其他功能可能会派上用场,例如parse_url、pathinfo,就像我之前提到的、服务器变量等...