在 Ubuntu 下开启 Apache2 伪静态(URL Rewrite),通常是为了让网站支持 mod_rewrite,比如 WordPress、ThinkPHP、Laravel 等框架都需要。下面按步骤说明。
mod_rewritesudo a2enmod rewrite
sudo systemctl restart apache2
默认站点通常是:
sudo nano /etc/apache2/sites-available/000-default.conf
如果你有自定义站点,比如:
sudo nano /etc/apache2/sites-available/your-site.conf
<VirtualHost *:80> 中添加或修改<Directory /var/www/html>
Options Indexes FollowSymLinks
AllowOverride All
Require all granted
</Directory>
⚠️ 重点:AllowOverride All 必须设置,否则 .htaccess 不会生效。
sudo systemctl restart apache2
.htaccess 实现伪静态.htaccesssudo nano /var/www/html/.htaccess
RewriteEngine On
# 将 index.php/xxx 转换为 /xxx
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ index.php/$1 [QSA,L]
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ index.php/$1 [QSA,L]
apache2ctl -M | grep rewrite
看到:
rewrite_module (shared)
说明已开启 ✅
访问:
http://your-domain.com/test
如果不再出现 404,而是被重写到 index.php,说明成功 ✅
.htaccess 不生效✅ 检查:
AllowOverride Allrewrite 模块Require all granted
.htaccess 语法错误RewriteEngine On 重复或位置错误sudo a2enmod rewrite
sudo nano /etc/apache2/sites-available/000-default.conf
# 设置 AllowOverride All
sudo systemctl restart apache2
如果你用的是 Nginx + Apache、Docker、宝塔面板 或 指定框架(如 Laravel / TP6),可以告诉我,我可以给你更精确的配置。