在 PHP 中实现伪静态,通常需要使用 URL 重写技术。以下是一个简单的示例,展示了如何使用 Apache 和 Nginx 服务器实现伪静态。
启用 mod_rewrite 模块: 确保你的 Apache 服务器已经启用了 mod_rewrite
模块。你可以在 Apache 配置文件(通常是 httpd.conf
或 apache2.conf
)中添加以下行来启用它:
LoadModule rewrite_module modules/mod_rewrite.so
配置 .htaccess
文件: 在你的网站根目录下创建或编辑 .htaccess
文件,添加以下内容:
RewriteEngine On RewriteBase / # 示例规则:将 /article/123 重写到 /article.php?id=123 RewriteRule ^article/([0-9]+)$ article.php?id=$1 [L]
配置 nginx.conf
文件: 打开你的 Nginx 配置文件(通常是 /etc/nginx/nginx.conf
或 /etc/nginx/sites-available/default
),找到 server
块并添加以下内容:
server { listen 80; server_name yourdomain.com; location / { try_files $uri $uri/ /index.php?$args; } location ~ \.php$ { include snippets/fastcgi-php.conf; fastcgi_pass unix:/var/run/php/php7.4-fpm.sock; # 根据你的 PHP 版本调整 } }
重启 Nginx: 保存配置文件并重启 Nginx 以应用更改:
sudo systemctl restart nginx
假设你有一个 PHP 文件 article.php
,它处理伪静态 URL:
<?php if ($_SERVER['REQUEST_URI'] == '/article/123') { // 处理请求 echo "Article ID: 123"; } else { // 显示 404 页面或其他错误 echo "Page not found"; } ?>
通过上述配置,你可以将类似 /article/123
的 URL 重写到 article.php?id=123
,从而实现伪静态。
mod_rewrite
模块和 .htaccess
文件。nginx.conf
文件中配置 try_files
和 location ~ \.php$
块。根据你的服务器类型,选择相应的配置方法即可实现伪静态。