apache实现example.com到www.example.com的301跳转,推荐用virtualhost+redirect permanent指令,无需mod_rewrite;若用.htaccess则需启用rewriteengine和allowoverride all,并配置rewritecond与rewriterule保留路径。

直接用 Apache 配置 301 跳转,把不带 www 的域名(如 example.com)统一跳到带 www 的版本(如 www.example.com),关键在于让所有访问 example.com 的请求,都返回 HTTP 状态码 301,并重定向到对应路径的 www.example.com 地址。
确认 mod_rewrite 已启用
Apache 默认可能未开启重写模块。先检查并启用它:
- Linux(Debian/Ubuntu):运行
a2enmod rewrite,然后重启 Apache(sudo systemctl restart apache2) - Linux(CentOS/RHEL):确保
LoadModule rewrite_module modules/mod_rewrite.so在httpd.conf中未被注释 - Windows:在
httpd.conf中取消#LoadModule rewrite_module modules/mod_rewrite.so前的#
推荐写法:用 VirtualHost + RedirectMatch(最简洁可靠)
编辑站点配置文件(如 /etc/apache2/sites-available/000-default.conf 或对应虚拟主机文件),添加两个 <virtualhost></virtualhost> 块:
<virtualhost>
ServerName example.com
Redirect permanent / http://www.example.com/
</virtualhost><p><virtualhost>
ServerName www.example.com
DocumentRoot /var/www/html</virtualhost></p><h1>其他常规配置(如 Directory、SSL 等)</h1><p></p>
✅ 优点:无需启用 RewriteEngine,语义清晰,Apache 原生支持,兼容性好,不易出错。
Apache Superset 是一个广泛采用的开源 BI 平台,用于 SQL 探索、图表构建和仪表板交付。当代理需要查询仓库数据、组装仪表板或使用成熟的分析界面解释指标而不是临时笔记本代码时,此技能非常有用。
备选写法:用 .htaccess(适合无权限改主配置时)
在网站根目录的 .htaccess 文件中加入:
RewriteEngine On
RewriteCond %{HTTP_HOST} ^example\.com$ [NC]
RewriteRule ^(.*)$ http://www.example.com/$1 [R=301,L]
⚠ 注意:AllowOverride All 必须在对应目录的主配置中启用,否则 .htaccess 不生效;HTTPS 站点请把 http 改为 https。
HTTPS 站点要同步处理
如果已部署 SSL,还需在 443 端口的 <virtualhost></virtualhost> 中做同样跳转,或统一用以下方式(更安全):
<virtualhost>
ServerName example.com
Redirect permanent / https://www.php.cn/link/4c74744a9c10b3001a1d9b87f86eb26f
</virtualhost><p><virtualhost>
ServerName example.com
Redirect permanent / <a href="https://www.php.cn/link/4c74744a9c10b3001a1d9b87f86eb26f">https://www.php.cn/link/4c74744a9c10b3001a1d9b87f86eb26f</a>
SSLEngine on</virtualhost></p><h1>SSL证书配置...</h1><p></p>
改完配置后,务必执行 sudo apachectl configtest 检查语法,再重启服务生效。跳转是否成功,可用 curl -I http://example.com 查看返回状态码是否为 301 Moved Permanently 及 Location 头是否正确。









