最推荐使用Redirect指令(简单可靠)或RewriteRule(灵活强大);Redirect适用于整体迁移等场景,需写在<VirtualHost>内、显式指定301/302、源路径以/开头、目标为完整URL、前缀匹配;RewriteRule适用于需正则、条件判断等复杂场景,依赖mod_rewrite且支持.htaccess。
apache 配置重定向跳转,最常用也最推荐的方式是使用 redirect 指令(简单可靠)或 rewriterule(灵活强大),具体选哪种取决于你的需求和权限。
用 Redirect 指令做 301/302 跳转
适合整体迁移、单页跳转、www 规范、HTTP→HTTPS 等场景,无需启用 mod_rewrite,语法简洁,执行效率高。
- 必须写在
<VirtualHost>块内,不能放在.htaccess - 源路径以
/开头(如/old),表示网站根目录下的 URI - 目标地址必须是完整 URL(含
http://或https://) - 状态码需显式指定:
Redirect 301(永久)、Redirect 302(临时),不写默认是 302 - 匹配方式为前缀匹配:写
Redirect 301 /blog /news,会同时匹配/blog、/blog/2024、/blog-post
常见写法示例:
- 强制跳转到带 www 的域名:
Redirect 301 / https://www.example.com/ - 整站迁移到新域名:
Redirect 301 / https://new-site.com/ - 单页跳转:
Redirect 301 /contact.html https://example.com/about.html - HTTP → HTTPS(80 端口配置中):
Redirect permanent / https://example.com/
用 RewriteRule 实现更精细的跳转
当你需要基于域名、参数、路径正则、条件判断(如仅对某类用户或某段路径生效)时,RewriteRule 更合适。它依赖 mod_rewrite 模块,且支持 .htaccess 和虚拟主机两种位置。
Apache Superset 是一个广泛采用的开源 BI 平台,用于 SQL 探索、图表构建和仪表板交付。当代理需要查询仓库数据、组装仪表板或使用成熟的分析界面解释指标而不是临时笔记本代码时,此技能非常有用。
- 启用模块:
LoadModule rewrite_module modules/mod_rewrite.so(确认未被注释) - 若用
.htaccess,对应目录的AllowOverride必须设为All - 开头必须加
RewriteEngine On - 常用条件判断:
RewriteCond %{HTTPS} off、RewriteCond %{HTTP_HOST} ^example.com、RewriteCond %{REQUEST_URI} ^/admin
典型用例:
- HTTP 强制跳 HTTPS:
RewriteEngine On<br>RewriteCond %{HTTPS} off<br>RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L] - 统一 www 前缀(非 www → www):
RewriteEngine On<br>RewriteCond %{HTTP_HOST} ^example.com [NC]<br>RewriteRule ^(.*)$ https://www.example.com/$1 [R=301,L] - 匹配图片请求并跳转到 CDN:
RewriteRule \.(jpg|jpeg|png|gif)$ https://cdn.example.com%{REQUEST_URI} [R=301,NC]
配置后必须做的三件事
- 检查语法:运行
sudo apache2ctl configtest(Debian/Ubuntu)或sudo httpd -t(CentOS/RHEL),确保返回Syntax OK - 重启服务:
sudo systemctl restart apache2或sudo systemctl restart httpd - 验证效果:用浏览器开发者工具 Network 面板查看响应头,或命令行执行
curl -I http://your-url,确认返回301 Moved Permanently及正确的Location字段
补充说明:RedirectMatch 和其他指令
如果要按正则匹配路径(比如所有 .php 文件、特定参数格式),可用 RedirectMatch:
RedirectMatch 301 ^/old/(.*)\.html$ https://example.com/new/$1.htmlRedirectMatch 301 ^/category/([0-9]+)/?$ https://example.com/topics/$1
其他实用指令:
-
Redirect gone /old-page.html:返回 410 Gone,告诉搜索引擎该页面已彻底删除 -
Redirect seeother /form.html https://example.com/thanks.html:返回 303,常用于表单提交后防重复提交 -
Redirect permanent和Redirect temp是别名,等价于Redirect 301和Redirect 302

















