在linux中apache将www域名301重定向到非www域名,需启用mod_rewrite模块、设置allowoverride all,并在虚拟主机中用redirect permanent指令或.htaccess中用rewritecond+rewriterule实现路径保留的跳转,最后语法检查并重启服务。

在 Linux 中配置 Apache 将带 www 的域名(如 www.example.com)301 永久重定向到非 www 域名(如 example.com),核心是启用重写模块并添加正确的跳转规则。操作不复杂,但需注意模块启用、配置位置和语法细节。
确认并启用 mod_rewrite 模块
Apache 默认可能未启用 URL 重写功能。需确保 mod_rewrite 已加载:
- 编辑主配置文件(常见路径:
/etc/apache2/apache2.conf或/etc/httpd/conf/httpd.conf) - 取消注释这一行(若存在且被注释):
LoadModule rewrite_module modules/mod_rewrite.so - 检查站点目录的
AllowOverride设置:确保对应<directory></directory>块中包含AllowOverride All,否则.htaccess方式无效
选择配置方式:推荐虚拟主机内直接设置
比修改全局配置更安全、更清晰。适用于大多数标准部署(如 Ubuntu/Debian 的 sites-available 或 CentOS 的 conf.d):
- 打开你的站点虚拟主机配置文件,例如:
/etc/apache2/sites-available/000-default.conf - 在
<virtualhost></virtualhost>块内(HTTP 端口),添加两行:
ServerName example.com<br>ServerAlias www.example.com<br>Redirect permanent / http://example.com/
⚠️ 注意:
• ServerName 设为首选域名(非 www)
• ServerAlias 显式声明 www 版本,让 Apache 接收该请求
• Redirect permanent 自动发出 301 状态码,语义明确、SEO 友好
备选方式:使用 .htaccess(适合无 root 权限场景)
若无法修改虚拟主机配置,可在网站根目录放置 .htaccess 文件:
- 创建文件:
.htaccess(注意开头的点) - 内容如下(替换
example.com为你的真实域名):
RewriteEngine On<br>RewriteCond %{HTTP_HOST} ^www\.example\.com$ [NC]<br>RewriteRule ^(.*)$ http://example.com/$1 [R=301,L]
✅ 这种写法支持保留路径(如 www.example.com/about → example.com/about),比 Redirect 更灵活;但前提是已满足前面的 AllowOverride All 要求。
生效前必须执行的操作
配置完成后不能直接生效,需验证并重启服务:
- 语法检查(避免配置错误导致 Apache 启动失败):
sudo apache2ctl configtest(Debian/Ubuntu)或sudo apachectl configtest(CentOS/RHEL) - 若返回
Syntax OK,再重启服务:sudo systemctl restart apache2(Debian/Ubuntu)
或sudo systemctl restart httpd(CentOS/RHEL) - 用浏览器或
curl -I http://www.example.com检查响应头是否含Location: http://example.com/和状态码301 Moved Permanently











