redirect

URI 重定向插件。

参数

Name Type Requirement Default Valid Description
http_to_https boolean 可选 false 当设置为 true 并且请求是 http 时,会自动 301 重定向为 https,uri 保持不变
uri string 可选 可以包含 Nginx 变量的 URI,例如:/test/index.html, $uri/index.html。你可以通过类似于 $ {xxx} 的方式引用变量,以避免产生歧义,例如:${uri}foo/index.html。若你需要保留 $ 字符,那么使用如下格式:/\$foo/index.html
regex_uri array[string] 可选 转发到上游的新 uri 地址, 使用正则表达式匹配来自客户端的 uri,当匹配成功后使用模板替换发送重定向到客户端, 未匹配成功时将客户端请求的 uri 转发至上游。uriregex_uri 不可以同时存在。例如:[“^/iresty/(.)/(.)/(.*)”,”/$1-$2-$3”] 第一个元素代表匹配来自客户端请求的 uri 正则表达式,第二个元素代表匹配成功后发送重定向到客户端的 uri 模板。
ret_code integer 可选 302 [200, …] 请求响应码
encode_uri boolean 可选 false 当设置为 true 时,对返回的 Location header进行编码,编码格式参考 RFC3986
append_query_string boolean optional false 当设置为true时,将请求url的query部分添加到Location里。如果在uriregex_uri中配置了query, 那么请求的query会被追加在这个query后,以&分隔。 注意:如果已经处理了query,比如使用了nginx变量$request_uri,那么启用此功能会造成query重复

http_to_httpsuriregex_uri 三个中只能配置一个。

示例

启用插件

下面是一个基本实例,为特定路由启用 redirect 插件:

  1. curl http://127.0.0.1:9080/apisix/admin/routes/1 -H 'X-API-KEY: edd1c9f034335f136f87ad84b625c8f1' -X PUT -d '
  2. {
  3. "uri": "/test/index.html",
  4. "plugins": {
  5. "redirect": {
  6. "uri": "/test/default.html",
  7. "ret_code": 301
  8. }
  9. },
  10. "upstream": {
  11. "type": "roundrobin",
  12. "nodes": {
  13. "127.0.0.1:80": 1
  14. }
  15. }
  16. }'

我们可以在新的 URI 中使用 Nginx 内置的任意变量:

  1. curl http://127.0.0.1:9080/apisix/admin/routes/1 -H 'X-API-KEY: edd1c9f034335f136f87ad84b625c8f1' -X PUT -d '
  2. {
  3. "uri": "/test",
  4. "plugins": {
  5. "redirect": {
  6. "uri": "$uri/index.html",
  7. "ret_code": 301
  8. }
  9. },
  10. "upstream": {
  11. "type": "roundrobin",
  12. "nodes": {
  13. "127.0.0.1:80": 1
  14. }
  15. }
  16. }'

测试

测试示例基于上述例子:

  1. $ curl http://127.0.0.1:9080/test/index.html -i
  2. HTTP/1.1 301 Moved Permanently
  3. Date: Wed, 23 Oct 2019 13:48:23 GMT
  4. Content-Type: text/html
  5. Content-Length: 166
  6. Connection: keep-alive
  7. Location: /test/default.html
  8. ...

我们可以检查响应码和响应头中的 Location 参数,它表示该插件已启用。

  1. 下面是一个实现 http https 跳转的示例:
  2. ```shell
  3. curl http://127.0.0.1:9080/apisix/admin/routes/1 -H 'X-API-KEY: edd1c9f034335f136f87ad84b625c8f1' -X PUT -d '
  4. {
  5. "uri": "/hello",
  6. "plugins": {
  7. "redirect": {
  8. "http_to_https": true
  9. }
  10. }
  11. }'

禁用插件

移除插件配置中相应的 JSON 配置可立即禁用该插件,无需重启服务:

  1. curl http://127.0.0.1:9080/apisix/admin/routes/1 -H 'X-API-KEY: edd1c9f034335f136f87ad84b625c8f1' -X PUT -d '
  2. {
  3. "uri": "/test/index.html",
  4. "plugins": {},
  5. "upstream": {
  6. "type": "roundrobin",
  7. "nodes": {
  8. "127.0.0.1:80": 1
  9. }
  10. }
  11. }'

这时该插件已被禁用。