温馨提示×

ubuntu apache2怎么开启伪静态

小樊
36
2026-09-17 09:39:43
栏目: 智能运维

在 Ubuntu 下使用 Apache2 开启“伪静态”(通常是指通过 .htaccess 实现 URL Rewrite),一般按下面步骤操作。


一、开启 rewrite 模块

Apache 默认可能没开启 rewrite 模块。

sudo a2enmod rewrite
sudo systemctl restart apache2

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

1. 编辑站点配置

找到你的站点配置文件(一般在 /etc/apache2/sites-available/ 下):

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

<VirtualHost *:80> 里加上:

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

如果你网站目录不是 /var/www/html,请改成你的实际路径。


2. 修改 apache2.conf(有些版本需要)

sudo nano /etc/apache2/apache2.conf

找到类似:

<Directory /var/www/>
    AllowOverride None

改成:

AllowOverride All

三、重启 Apache

sudo systemctl restart apache2

四、使用 .htaccess 实现伪静态

在网站根目录创建或编辑 .htaccess

sudo nano /var/www/html/.htaccess

示例(ThinkPHP / 通用伪静态):

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

五、常见框架示例

✅ WordPress

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

✅ Laravel

<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.php [L]
</IfModule>

六、排查问题

  1. 伪静态不生效

    • 确认 AllowOverride All
    • 确认 rewrite 模块已开启
    • 清除浏览器缓存
  2. 403 / 500 错误

    • 查看错误日志:
    sudo tail -f /var/log/apache2/error.log
    

如果你用的是 特定程序(WordPress / ThinkPHP / Laravel / Discuz 等),可以告诉我,我可以直接给你对应的 .htaccess 和配置。

0