在 Ubuntu 上“启用 PHP 重写规则”,通常指的是让 Apache/Nginx 支持 URL Rewrite(重写),常用于 ThinkPHP、Laravel、WordPress 等 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
在项目根目录创建 .htaccess:
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php/$1 [L]
✅ 适用于:ThinkPHP、Laravel、WordPress 等
编辑配置文件:
sudo nano /etc/nginx/sites-available/default
示例(PHP + 重写):
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 reload nginx
✅ 重写不生效?
AllowOverride Alltry_files✅ 404 错误?
DocumentRoot如果你能告诉我:
我可以给你精确到配置文件的重写规则。