diff --git a/apisix/plugins/proxy-rewrite.lua b/apisix/plugins/proxy-rewrite.lua index eff3c2a256b9..c1d7ec4f5d54 100644 --- a/apisix/plugins/proxy-rewrite.lua +++ b/apisix/plugins/proxy-rewrite.lua @@ -195,22 +195,20 @@ function _M.rewrite(conf, ctx) ctx.var.upstream_uri = upstream_uri end - if not conf.headers then - return - end - - if not conf.headers_arr then - conf.headers_arr = {} + if conf.headers then + if not conf.headers_arr then + conf.headers_arr = {} - for field, value in pairs(conf.headers) do - core.table.insert_tail(conf.headers_arr, field, value) + for field, value in pairs(conf.headers) do + core.table.insert_tail(conf.headers_arr, field, value) + end end - end - local field_cnt = #conf.headers_arr - for i = 1, field_cnt, 2 do - core.request.set_header(ctx, conf.headers_arr[i], - core.utils.resolve_var(conf.headers_arr[i+1], ctx.var)) + local field_cnt = #conf.headers_arr + for i = 1, field_cnt, 2 do + core.request.set_header(ctx, conf.headers_arr[i], + core.utils.resolve_var(conf.headers_arr[i+1], ctx.var)) + end end if conf.method then diff --git a/t/plugin/proxy-rewrite3.t b/t/plugin/proxy-rewrite3.t index 31364d08ecf3..f98de527fa3f 100644 --- a/t/plugin/proxy-rewrite3.t +++ b/t/plugin/proxy-rewrite3.t @@ -79,7 +79,7 @@ passed === TEST 2: hit route(upstream uri: should be /hello) --- request GET /hello ---- grep_error_log_out +--- error_log plugin_proxy_rewrite get method: POST @@ -125,7 +125,7 @@ passed === TEST 4: hit route(upstream uri: should be /hello) --- request GET /hello ---- grep_error_log_out +--- error_log plugin_proxy_rewrite get method: GET @@ -151,3 +151,52 @@ plugin_proxy_rewrite get method: GET --- response_body property "method" validation failed: matches none of the enum values done + + + +=== TEST 6: set route(rewrite method with headers) +--- config + location /t { + content_by_lua_block { + local t = require("lib.test_admin").test + local code, body = t('/apisix/admin/routes/1', + ngx.HTTP_PUT, + [[{ + "methods": ["GET"], + "plugins": { + "proxy-rewrite": { + "uri": "/plugin_proxy_rewrite", + "method": "POST", + "scheme": "http", + "host": "apisix.iresty.com", + "headers":{ + "x-api-version":"v1" + } + } + }, + "upstream": { + "nodes": { + "127.0.0.1:1980": 1 + }, + "type": "roundrobin" + }, + "uri": "/hello" + }]] + ) + + if code >= 300 then + ngx.status = code + end + ngx.say(body) + } + } +--- response_body +passed + + + +=== TEST 7: hit route(with header) +--- request +GET /hello +--- error_log +plugin_proxy_rewrite get method: POST