PHP 伪静态使用两种方法:通过 .htaccess 文件,添加 RewriteEngine 和 RewriteRule 配置,将类似 index.php?page=example.html 的动态 URL 重写为 index.php?page=example;在 PHP 脚本中包含 rewrite 规则,例如 RewriteEngine On;RewriteRule ^page/([0-9]+).html$ page.php?id=$1 [L]; 将 page/123.html 重写为 pag

PHP 伪静态实现
伪静态是一种使动态 URL 看起来像静态 URL 的技术。PHP 可以通过两种主要方法实现伪静态:
1. 使用 .htaccess 文件
.htaccess 是一个隐藏文件,它允许您配置 Apache Web 服务器的行为。要使用 .htaccess 实现伪静态,请执行以下步骤:
立即学习“PHP免费学习笔记(深入)”;
- 在网站根目录创建一个名为 ".htaccess" 的文件。
- 添加以下代码:
<code>RewriteEngine On RewriteRule ^([a-zA-Z0-9_-]+)\.html$ index.php?page=$1 [L]</code>
- 将 "index.php" 替换为您要使用的 PHP 脚本。
- 将 "page" 替换为 URL 中要提取的参数的名称。
2. 使用 PHP 的 rewrite 规则
也可以在 PHP 脚本中使用 rewrite 规则来实现伪静态。要使用此方法,请执行以下步骤:
- 在您的 PHP 脚本中,包含以下代码:
<code class="php">RewriteEngine On; RewriteRule ^([a-zA-Z0-9_-]+)\.html$ index.php?page=$1 [L];</code>
- 将 "index.php" 替换为您要使用的 PHP 脚本。
- 将 "page" 替换为 URL 中要提取的参数的名称。
示例
假设您有一个名为 "page.php" 的 PHP 脚本,它接受一个名为 "id" 的参数。您可以通过以下方式实现伪静态:
.htaccess 文件
<code>RewriteEngine On RewriteRule ^page/([0-9]+)\.html$ page.php?id=$1 [L]</code>
PHP 脚本
<code class="php">RewriteEngine On; RewriteRule ^page/([0-9]+)\.html$ page.php?id=$1 [L];</code>
这将允许您使用以下 URL 访问 "page.php" 脚本:
<code>http://example.com/page/123.html</code>
这将等同于访问以下 URL:
<code>http://example.com/page.php?id=123</code>











