在 Ubuntu 下让 PHP 实现伪静态(URL Rewrite),通常是通过 Web 服务器(Apache 或 Nginx) 来完成的,PHP 本身不直接处理伪静态。
下面分别说明 Apache 和 Nginx 的常见做法。
sudo a2enmod rewrite
sudo systemctl restart apache2
编辑站点配置:
sudo nano /etc/apache2/sites-available/000-default.conf
在 <VirtualHost> 中添加或确认:
<Directory /var/www/html>
AllowOverride All
</Directory>
重启 Apache:
sudo systemctl restart apache2
在项目根目录(如 /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
处理
编辑站点配置:
sudo nano /etc/nginx/sites-available/default
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
sudo nginx -t
sudo systemctl reload nginx
例如 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 |
如果你愿意,可以告诉我:
/user/1、/post/123.html)我可以给你 精准的伪静态规则。