Apache URL重写本质是通过RewriteRule实现内部重写(地址栏不变)或外部重定向(地址栏变化),需先启用mod_rewrite模块、设置AllowOverride All,并以RewriteEngine On开启引擎,再按需配置规则。
Apache URL 重写实现静态页面跳转,本质是用 RewriteRule 把一个看似静态的路径(如 /about.html)映射到真实存在的静态文件,或转发给动态脚本处理。关键不在于“跳转”,而在于内部重写(不改变浏览器地址栏)或外部重定向(地址栏变化),需按需选择。
这是所有规则生效的前提:
mod_rewrite 模块已加载:在 httpd.conf 中取消注释这一行:LoadModule rewrite_module modules/mod_rewrite.so
.htaccess,必须允许覆盖:在对应目录的 <Directory> 块中设为 AllowOverride All,并启用 Options FollowSymLinks
httpd.conf 或 .htaccess)添加:RewriteEngine On
用户访问 /about.html,服务器悄悄读取 about.php 或 pages/about.html 的内容返回,地址栏不变。
.html 请求交给 PHP 处理:RewriteRule ^(.+).html$ $1.php [L]
→ 访问 /contact.html 实际执行 contact.php
RewriteRule ^/news/(d+).html$ /static/news/$1.html [L]
→ /news/2024.html 对应磁盘路径 /static/news/2024.html
index.html:RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^.*$ /index.html [L]
用户访问旧地址,浏览器收到 301 或 302 响应,自动跳转到新地址。适用于页面迁移、域名更换等场景。
RewriteRule ^/old-page.html$ /new-page.html [R=301,L]
RewriteRule ^/temp.html$ https://example.com/maintenance.html [R=302,L]
example.com 到 www.example.com):RewriteCond %{HTTP_HOST} ^example.com [NC]
RewriteRule ^(.*)$ https://www.example.com/$1 [R=301,L]
避免踩坑,提升稳定性:
.htaccess 中,匹配路径不带开头 /(如 ^about.html$);在 httpd.conf 的虚拟主机内,要加(如 ^/about.html$)[L] 标志,防止后续规则干扰;多个条件用 RewriteCond 配合,逻辑更清晰.、问号 ?、加号 + 等需用反斜杠转义,例如 .html、?id=
curl -I 查看响应头状态码,确认是否为 200(内部重写)或 301/302(重定向)