温馨提示×

ubuntu php如何做伪静态

小樊
36
2026-09-13 10:00:25
栏目: 编程语言

在 Ubuntu 下让 PHP 实现伪静态(URL Rewrite),通常是通过 Web 服务器(Apache 或 Nginx) 来完成的,PHP 本身不直接处理伪静态。

下面分别说明 ApacheNginx 的常见做法。


一、Apache + PHP(最常见)

1. 开启 rewrite 模块

sudo a2enmod rewrite
sudo systemctl restart apache2

2. 修改站点配置(AllowOverride)

编辑站点配置:

sudo nano /etc/apache2/sites-available/000-default.conf

<VirtualHost> 中添加或确认:

<Directory /var/www/html>
    AllowOverride All
</Directory>

重启 Apache:

sudo systemctl restart apache2

3. 编写 .htaccess(伪静态规则)

在项目根目录(如 /var/www/html)创建 .htaccess

示例:把所有请求转发给 index.php

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php/$1 [L]

访问:

http://domain.com/article/123

实际由:

index.php/article/123

处理


二、Nginx + PHP(推荐生产环境)

1. 修改 Nginx 配置

编辑站点配置:

sudo nano /etc/nginx/sites-available/default

2. 配置伪静态(try_files)

server {
    listen 80;
    server_name yourdomain.com;
    root /var/www/html;
    index index.php index.html;

    location / {
        try_files $uri $uri/ /index.php?$query_string;
    }

    location ~ \.php$ {
        include snippets/fastcgi-php.conf;
        fastcgi_pass unix:/var/run/php/php8.1-fpm.sock;
    }
}

根据你 PHP 版本调整 php8.1-fpm.sock

3. 测试并重载

sudo nginx -t
sudo systemctl reload nginx

三、PHP 中如何接收伪静态参数

例如 URL:

/article/123

Apache:

$uri = $_SERVER['REQUEST_URI'];
// /article/123

Nginx:

$path = $_GET['path'] ?? '';

或使用前端路由解析:

$segments = explode('/', trim($_SERVER['REQUEST_URI'], '/'));

四、常见伪静态示例

新闻详情页

RewriteRule ^news/([0-9]+)\.html$ news.php?id=$1 [L]

访问:

/news/123.html

五、总结

服务器 伪静态方式
Apache .htaccess + mod_rewrite
Nginx try_files / rewrite
PHP 解析 REQUEST_URI

如果你愿意,可以告诉我:

  • 用的是 Apache 还是 Nginx
  • PHP 版本
  • 具体想做的 URL 格式(如 /user/1/post/123.html

我可以给你 精准的伪静态规则

0