温馨提示×

如何开启ubuntu apache2伪静态

小樊
37
2026-08-16 19:41:23
栏目: 智能运维

Ubuntu 下开启 Apache2 伪静态(URL Rewrite),通常是为了让网站支持 mod_rewrite,比如 WordPress、ThinkPHP、Laravel 等框架都需要。下面按步骤说明。


一、开启 Apache2 的 rewrite 模块

1️⃣ 启用 mod_rewrite

sudo a2enmod rewrite

2️⃣ 重启 Apache2

sudo systemctl restart apache2

二、修改 Apache 站点配置(非常关键)

1️⃣ 编辑站点配置文件

默认站点通常是:

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

如果你有自定义站点,比如:

sudo nano /etc/apache2/sites-available/your-site.conf

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

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

⚠️ 重点AllowOverride All 必须设置,否则 .htaccess 不会生效。

3️⃣ 保存后重启 Apache

sudo systemctl restart apache2

三、使用 .htaccess 实现伪静态

1️⃣ 在网站根目录创建 .htaccess

sudo nano /var/www/html/.htaccess

2️⃣ 示例规则(通用)

RewriteEngine On

# 将 index.php/xxx 转换为 /xxx
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]

✅ ThinkPHP

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

四、确认是否生效

1️⃣ 检查模块是否加载

apache2ctl -M | grep rewrite

看到:

rewrite_module (shared)

说明已开启 ✅

2️⃣ 访问测试

访问:

http://your-domain.com/test

如果不再出现 404,而是被重写到 index.php,说明成功 ✅


五、常见问题排查

.htaccess 不生效

✅ 检查:

  • AllowOverride All
  • 是否重启 Apache
  • 是否启用了 rewrite 模块

❌ 403 Forbidden

Require all granted

❌ 500 错误

  • .htaccess 语法错误
  • RewriteEngine On 重复或位置错误

六、总结(最简流程)

sudo a2enmod rewrite
sudo nano /etc/apache2/sites-available/000-default.conf
# 设置 AllowOverride All
sudo systemctl restart apache2

如果你用的是 Nginx + ApacheDocker宝塔面板指定框架(如 Laravel / TP6),可以告诉我,我可以给你更精确的配置。

0