在 Ubuntu 下让 PHP 项目支持伪静态(URL Rewrite),通常取决于你使用的 Web 服务器。最常见的是 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>
然后重启:
sudo systemctl restart apache2
.htaccess示例(把所有请求转发到 index.php):
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php/$1 [L]
✅ 这样 example.com/article/1 就会交给 index.php 处理。
sudo nano /etc/nginx/sites-available/default
示例配置:
server {
listen 80;
server_name example.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:/run/php/php8.1-fpm.sock;
}
}
sudo nginx -t
sudo systemctl restart nginx
✅ Nginx 不需要 .htaccess,伪静态全在配置里。
.htaccesslocation / {
if (!-e $request_filename) {
rewrite ^(.*)$ /index.php?s=$1 last;
}
}
location / {
try_files $uri $uri/ /index.php?$query_string;
}
nginx -s reload如果你能告诉我:
我可以直接给你可复制的配置文件。