在 Ubuntu 下配置 PHP 的“伪静态”(通常指 URL Rewrite,如 /index.php?a=1 → /a/1.html),主要分为 Web 服务器配置 和 PHP 程序配合 两部分。常见情况是使用 Apache 或 Nginx。
sudo a2enmod rewrite
sudo systemctl restart apache2
编辑站点配置:
sudo nano /etc/apache2/sites-available/000-default.conf
在 <VirtualHost *:80> 中加入:
<Directory /var/www/html>
AllowOverride All
</Directory>
重启 Apache:
sudo systemctl restart apache2
在网站根目录(如 /var/www/html)创建:
nano /var/www/html/.htaccess
示例(ThinkPHP / 通用):
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ index.php/$1 [QSA,L]
或常见 .html 伪静态:
RewriteRule ^article-([0-9]+).html$ article.php?id=$1
sudo nano /etc/nginx/sites-available/default
server {
listen 80;
server_name localhost;
root /var/www/html;
location / {
index index.php index.html;
try_files $uri $uri/ /index.php?$query_string;
}
location ~ \.php$ {
include snippets/fastcgi-php.conf;
fastcgi_pass unix:/run/php/php8.1-fpm.sock;
}
}
sudo systemctl restart nginx
伪静态只是“转发 URL”,PHP 仍需正确解析:
$_GET示例:
// article.php
$id = $_GET['id'];
echo $id;
.htaccess,Nginx 用 try_files.htaccesstry_files# Apache 是否开启 rewrite
apache2ctl -M | grep rewrite
# Nginx 配置是否正确
nginx -t
如果你能告诉我:
我可以直接给你 可复制的完整配置。