PHP 重写规则配置

PHP 重写规则配置,又称拟静态,可以将动态 URL 转换为更美观、更友好的静态 URL。它可以通过以下步骤实现:

  1. .htaccess 文件中添加如下代码:
RewriteEngine On
RewriteRule ^index.php/(.*)$ /$1 [L]
  1. 在您的 PHP 脚本中使用 $_SERVER['REQUEST_URI'] 来获取原始 URL,然后对其进行解析以提取所需的参数。

  2. 根据提取的参数,生成所需的静态 URL,并通过 header() 函数进行重定向。

示例:

$uri = $_SERVER['REQUEST_URI'];
$parts = parse_url($uri);
$path = $parts['path'];

if (preg_match('/^/blog/(d+)$/', $path, $matches)) {
    $id = $matches[1];
    $staticUrl = '/blog/' . $id . '.html';
    header('Location: ' . $staticUrl);
    exit;
}

这样就可以将动态 URL /blog/1 转换为静态 URL /blog/1.html

txt 文件大小:1.35KB