在 PHP 中实现伪静态,通常需要使用 URL 重写技术。以下是一个简单的示例,展示了如何使用 Apache 和 Nginx 服务器实现伪静态。
Apache 服务器
-
启用 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 服务器
-
配置
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 代码
假设你有一个 PHP 文件 article.php,它处理伪静态 URL:
if ($_SERVER['REQUEST_URI'] == '/article/123') {
// 处理请求
echo "Article ID: 123";
} else {
// 显示 404 页面或其他错误
echo "Page not found";
}
?>
通过上述配置,你可以将类似 /article/123 的 URL 重写到 article.php?id=123,从而实现伪静态。
总结
- Apache:使用
mod_rewrite模块和.htaccess文件。 - Nginx:在
nginx.conf文件中配置try_files和location ~ \.php$块。
根据你的服务器类型,选择相应的配置方法即可实现伪静态。
以上就是关于“怎么用php实现伪静态”的相关介绍,筋斗云是国内较早的云主机应用的服务商,拥有10余年行业经验,提供丰富的云服务器、租用服务器等相关产品服务。云服务器资源弹性伸缩,主机vCPU、内存性能强悍、超高I/O速度、故障秒级恢复;电子化备案,提交快速,专业团队7×24小时服务支持!
简单好用、高性价比云服务器租用链接:https://www.jindouyun.cn/product/cvm