温馨提示×

如何开启Ubuntu Apache伪静态

小樊
40
2026-08-01 05:17:34
栏目: 智能运维

Ubuntu 下给 Apache 开启 伪静态(URL Rewrite),通常就是启用 mod_rewrite 并正确配置 .htaccess 或虚拟主机。下面是完整步骤:


一、启用 Apache 的 rewrite 模块

sudo a2enmod rewrite

启用后重启 Apache:

sudo systemctl restart apache2

二、修改 Apache 配置,允许 .htaccess 生效(关键)

默认情况下,Apache 可能不允许 .htaccess 覆盖规则

1️⃣ 编辑站点配置文件

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

(如果你用的是其他虚拟主机,请编辑对应文件)

2️⃣ 在 <VirtualHost> 中添加或修改:

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

/var/www/html 换成你的网站目录

3️⃣ 保存后重启 Apache

sudo systemctl restart apache2

三、创建或编辑 .htaccess 文件

进入网站根目录:

cd /var/www/html

创建 .htaccess

nano .htaccess

示例伪静态规则(常见)

✅ 开启 RewriteEngine

RewriteEngine On

✅ 将 index.php?page=xxx 伪静态为 /page/xxx

RewriteRule ^page/([0-9]+)$ index.php?page=$1 [L]

✅ ThinkPHP / Laravel / WordPress 常用

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

四、确认是否生效

  1. 在网站根目录创建一个测试文件:
echo "<?php phpinfo();" > info.php
  1. 访问:
http://你的IP/info.php
  1. 搜索 mod_rewrite,确认已加载

五、常见问题排查

❌ 伪静态不生效

✅ 检查:

  • AllowOverride All 是否设置
  • 是否重启 Apache
  • .htaccess 是否在正确目录
  • 文件是否以 .htaccess 开头(不是 htaccess.txt)

❌ 403 Forbidden

Require all granted

❌ 500 错误

检查 .htaccess 语法是否正确


六、快速总结(命令版)

sudo a2enmod rewrite
sudo nano /etc/apache2/sites-enabled/000-default.conf
# 添加 AllowOverride All
sudo systemctl restart apache2

如果你用的是 WordPress / ThinkPHP / Laravel / 宝塔 / Docker,可以告诉我,我可以给你对应环境的专用配置

0