温馨提示×

Ubuntu怎么启用PHP重写规则

小樊
49
2026-09-04 13:27:32
栏目: 编程语言

在 Ubuntu 上“启用 PHP 重写规则”,通常指的是让 Apache/Nginx 支持 URL Rewrite(重写),常用于 ThinkPHP、Laravel、WordPress 等 PHP 项目。

下面分 Apache 和 Nginx 两种常见情况说明。


一、Apache 启用重写规则(最常用)

1. 启用 rewrite 模块

sudo a2enmod rewrite
sudo systemctl restart apache2

2. 修改站点配置,允许 .htaccess 生效

编辑你的站点配置文件(如):

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

在 <VirtualHost *:80> 中添加:

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

保存后重启 Apache:

sudo systemctl restart apache2

3. 使用 .htaccess(示例)

在项目根目录创建 .htaccess:

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

✅ 适用于:ThinkPHP、Laravel、WordPress 等


二、Nginx 启用 PHP 重写规则

1. 修改 Nginx 站点配置

编辑配置文件:

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;
    }
}

2. 测试并重载 Nginx

sudo nginx -t
sudo systemctl reload nginx

三、常见问题排查

✅ 重写不生效?

  • Apache:确认 AllowOverride All
  • Nginx:确认 try_files
  • 文件权限问题

✅ 404 错误?

  • 检查 DocumentRoot
  • 检查 PHP-FPM 是否运行

如果你能告诉我:

  • 用的是 Apache 还是 Nginx
  • PHP 框架(Laravel / ThinkPHP / 原生)

我可以给你精确到配置文件的重写规则。

0 踩