温馨提示×

ubuntu apache2如何设置伪静态

小樊
36
2026-10-05 05:00:03
栏目: 智能运维

在 Ubuntu 下使用 Apache2 设置“伪静态”(通常是指通过 .htaccess 或虚拟主机配置实现 URL Rewrite),一般步骤如下:


一、开启 Apache 的 rewrite 模块

伪静态依赖 mod_rewrite 模块。

sudo a2enmod rewrite
sudo systemctl restart apache2

二、修改 Apache 配置,允许 .htaccess 生效

1. 修改虚拟主机配置(推荐)

编辑你的站点配置,例如:

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

在 <VirtualHost *:80> 中添加或修改:

<Directory /var/www/html>
    AllowOverride All
    Require all granted
</Directory>

保存后重启 Apache:

sudo systemctl restart apache2

⚠️ 默认 Ubuntu 中 AllowOverride None,不改成 All,.htaccess 是不生效的。


三、使用 .htaccess 设置伪静态规则

在网站根目录(如 /var/www/html)创建或编辑 .htaccess:

sudo nano /var/www/html/.htaccess

示例 1:把 index.php?id=1 伪静态为 /article/1

RewriteEngine On
RewriteRule ^article/([0-9]+)$ index.php?id=$1 [L]

访问:

/article/1  →  index.php?id=1

示例 2:ThinkPHP 伪静态

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

示例 3:WordPress 伪静态

RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]

四、直接在 Apache 配置中写 Rewrite(不推荐但更高效)

也可以不写 .htaccess,直接写在 <VirtualHost> 中:

<VirtualHost *:80>
    ServerName example.com
    DocumentRoot /var/www/html

    <Directory /var/www/html>
        AllowOverride All
        Require all granted
    </Directory>

    RewriteEngine On
    RewriteRule ^article/([0-9]+)$ index.php?id=$1 [L]
</VirtualHost>

五、常见问题排查

1. .htaccess 不生效

  • 没开 rewrite 模块
  • AllowOverride 不是 All
  • 没重启 Apache

2. 404 错误

  • 规则写错
  • 真实文件被重写覆盖

3. 查看错误日志

sudo tail -f /var/log/apache2/error.log

如果你能告诉我:

  • 使用的程序(WordPress / ThinkPHP / 原生 PHP / Laravel 等)
  • Apache 版本
  • 想实现的具体 URL 效果

我可以给你 精确可用的伪静态规则。

0 踩