Apache二级域名跳转需先确保mod_rewrite模块启用、AllowOverride设为All、DNS解析生效;再用RewriteCond匹配转义后的域名,配合RewriteRule实现301跳转并保留路径,[R=301,L]确保永久重定向且终止后续规则。
Apache mod_rewrite 域名跳转不是写几行代码就完事,关键在于匹配条件准确、跳转逻辑清晰、状态码选对,且环境已就绪。下面从真实部署角度,直接讲清楚怎么配、为什么这么配、容易踩哪些坑。
很多跳转不生效,根本不是规则写错,而是底层没打开。必须检查三项:
httpd -M | grep rewrite 或 a2enmod rewrite(Debian系),确认 rewrite_module 已加载;<Directory> 区块里,AllowOverride 必须设为 All 或至少包含 FileInfo;m.example.com)正确解析到当前服务器 IP,CNAME 或 A 记录均需生效(可用 dig m.example.com 验证)。比如用户访问 m.example.com/product/123,你想让它 301 跳到 www.example.com/m/product/123,保留路径结构:
RewriteEngine OnRewriteCond %{HTTP_HOST} ^m.example.com$ [NC]RewriteRule ^(.*)$ https://www.example.com/m/$1 [R=301,L]
注意点:
^m.example.com$ 中的点要转义,否则 m.examplecom 也会被误匹配;[R=301,L] 表示永久跳转 + 立即终止后续规则,避免与其他重写冲突;当有 www.example.com、example.com、shop.example.com 多个入口,想全部规范到 https://www.example.com:
RewriteEngine OnRewriteCond %{HTTP_HOST} !^www.example.com$ [NC]RewriteCond %{HTTP_HOST} !^$RewriteRule ^(.*)$ https://www.example.com/$1 [R=301,L]
说明:
RewriteCond 排除主域名,第二个排除空 Host(防异常请求);! 否定逻辑比逐个写 OR 更简洁安全;shop.example.com/about → www.example.com/about。如果目标地址是 HTTPS,但用户可能从 HTTP 访问二级域名,可合并判断:
RewriteEngine OnRewriteCond %{HTTP_HOST} ^blog.example.com$ [NC]RewriteCond %{HTTPS} offRewriteRule ^(.*)$ https://blog.example.com/$1 [R=301,L]
这个组合确保:只对 blog.example.com 生效,且仅当当前非 HTTPS 时才跳转。若已是 HTTPS,则跳过该规则,避免循环重定向。
不复杂但容易忽略细节,配完务必用 curl -I http://m.example.com 和 curl -I https://m.example.com 分别测试响应头中的 Location 和状态码是否符合预期。