在 Ubuntu 下使用 Apache2 开启“伪静态”(通常是指通过 .htaccess 实现 URL Rewrite),一般按下面步骤操作。
Apache 默认可能没开启 rewrite 模块。
sudo a2enmod rewrite
sudo systemctl restart apache2
找到你的站点配置文件(一般在 /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,请改成你的实际路径。
sudo nano /etc/apache2/apache2.conf
找到类似:
<Directory /var/www/>
AllowOverride None
改成:
AllowOverride All
sudo systemctl restart apache2
在网站根目录创建或编辑 .htaccess:
sudo nano /var/www/html/.htaccess
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ index.php/$1 [QSA,L]
</IfModule>
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.php [L]
</IfModule>
伪静态不生效
AllowOverride Allrewrite 模块已开启403 / 500 错误
sudo tail -f /var/log/apache2/error.log
如果你用的是 特定程序(WordPress / ThinkPHP / Laravel / Discuz 等),可以告诉我,我可以直接给你对应的 .htaccess 和配置。