Apache 的 Rewrite 模块(mod_rewrite)是一个非常强大的 URL 重写引擎,允许你基于各种条件重写 URL。以下是启用和使用这个模块的详细步骤:
首先检查 mod_rewrite 是否已经启用:
apache2ctl -M | grep rewrite
或者对于较旧版本的 Apache:
httpd -M | grep rewrite
如果看到 rewrite_module
表示已启用。
sudo a2enmod rewrite
sudo systemctl restart apache2
编辑 /etc/httpd/conf/httpd.conf
文件,确保有以下行(取消注释):
LoadModule rewrite_module modules/mod_rewrite.so
然后重启 Apache:
sudo systemctl restart httpd
编辑 Apache 的虚拟主机配置文件(通常在 /etc/apache2/sites-available/000-default.conf
或类似位置):
<Directory /var/www/html>
Options Indexes FollowSymLinks
AllowOverride All
Require all granted
</Directory>
关键点是 AllowOverride All
,这允许 .htaccess 文件覆盖配置。
应用更改:
# Ubuntu/Debian
sudo systemctl restart apache2
# CentOS/RHEL
sudo systemctl restart httpd
在网站根目录(如 /var/www/html
)创建 .htaccess
文件:
RewriteEngine On
RewriteRule ^test$ index.html [NC]
这会使得访问 /test
时显示 index.html
内容。
访问 http://yourdomain.com/test
,应该看到与 index.html
相同的内容。
RewriteEngine On
RewriteRule ^oldpage\.html$ newpage.html [R=301,L]
RewriteCond %{HTTP_HOST} ^example\.com [NC]
RewriteRule ^(.*)$ http://www.example.com/$1 [R=301,L]
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}\.php -f
RewriteRule ^(.*)$ $1.php
重写不生效:
AllowOverride All
已设置tail -f /var/log/apache2/error.log
.htaccess
文件名正确(前面有点)500 服务器错误:
.htaccess
语法错误权限问题:
.htaccess
文件通过以上步骤,你应该能够成功启用并使用 Apache 的 Rewrite 模块来实现各种 URL 重写需求。