a6-plugin-redirect
概览
redirect 插件会向客户端返回 HTTP 重定向响应(如 301、302 等),
可将客户端重定向到新的 URI、强制使用 HTTPS,或使用正则表达式执行复杂的路径转换。与 proxy-rewrite(只会在转发到上游前重写请求)不同,该插件会直接向客户端返回重定向响应。
适用场景
- 通过将所有 HTTP 请求重定向到 HTTPS 来强制使用 HTTPS。
- 将旧 URL 重定向到新地址(301 永久重定向)。
- 使用正则捕获组进行基于模式的 URI 重写
- 重定向到外部域名。
- 在重定向期间追加或保留查询字符串。
插件配置参考(路由/服务)
| 字段 | 类型 | 是否必填 | 默认值 | 说明 |
|---|---|---|---|---|
http_to_https | boolean | 否 | false | 将 HTTP 重定向到 HTTPS,保留 URI 和查询字符串,并使用 301 状态码。 |
uri | string | 否 | — | 目标重定向 URI。支持 Nginx 变量($uri、$host 等),也可以是绝对 URL。 |
regex_uri | array[string] | 否 | — | 包含两个元素的数组:["regex_pattern", "replacement"]。PCRE 正则表达式支持捕获组。 |
ret_code | integer | 否 | 302 | 重定向响应使用的 HTTP 状态码。 |
encode_uri | boolean | 否 | false | 根据 RFC 3986 对 Location 请求头中的 URI 编码。 |
append_query_string | boolean | 否 | false | 将原始请求查询字符串追加到重定向 Location。 |
互斥关系:http_to_https、uri 和 regex_uri 一次只能配置其中一项。
注意:http_to_https 和 append_query_string 不能同时使用(http_to_https 已经会保留查询字符串)。
HTTPS 端口选择(用于 http_to_https)
当 http_to_https 为 true 时,HTTPS 端口按以下优先级确定:
plugin_attr.redirect.https_port在conf/config.yaml- 如果配置了 SSL,则从
apisix.ssl.listen中选择随机端口。 - 默认值:
443
分步指南:在路由上启用 redirect
1. HTTP 到 HTTPS 重定向
在 APISIX 中启用 HTTPS 重定向:
a6 route create -f - <<'EOF'
{
"id": "force-https",
"uri": "/*",
"plugins": {
"redirect": {
"http_to_https": true
}
}
}
EOF
结果:http://example.com/path?q=1 → https://example.com/path?q=1(301)
2. 简单 URI 重定向(永久移动)
a6 route create -f - <<'EOF'
{
"id": "old-to-new",
"uri": "/old-page",
"plugins": {
"redirect": {
"uri": "/new-page",
"ret_code": 301
}
}
}
EOF
3. 使用捕获组进行正则重定向
a6 route create -f - <<'EOF'
{
"id": "regex-redirect",
"uri": "/blog/*",
"plugins": {
"redirect": {
"regex_uri": ["^/blog/(\\d{4})/(\\d{2})/(.*)$", "/articles/$1-$2-$3"],
"ret_code": 301
}
}
}
EOF
结果:/blog/2024/03/my-post → /articles/2024-03-my-post
常见模式
重定向到外部域名
{
"plugins": {
"redirect": {
"uri": "https://new-domain.com/api/v2",
"ret_code": 301
}
}
}
使用 NGINX 变量重定向
{
"plugins": {
"redirect": {
"uri": "https://new-domain.com$request_uri",
"ret_code": 301
}
}
}
保留完整的原始路径和查询字符串。
追加尾部斜杠
{
"plugins": {
"redirect": {
"uri": "$uri/",
"ret_code": 301
}
}
}