使用EventBridge调用API Gateway时,如何防止路径参数中的斜杠被编码?
Great question—this is a common gotcha with EventBridge-to-API Gateway integrations, and the good news is there's a straightforward fix without needing to rewrite your ECS service routes.
The root issue here is that EventBridge automatically URL-encodes special characters (including slashes /) when using path_parameter_values, and your current Terraform configuration has redundant path settings that trigger this encoding unnecessarily. Here's how to resolve it:
1. Remove the Redundant http_target Configuration
Your aws_cloudwatch_event_target includes both a full path in the ARN and a path_parameter_values block—this is the source of the encoding problem. The ARN already explicitly defines the API Gateway endpoint path (/devstage/POST/foo/events/ebevent), so the http_target block is redundant and causes EventBridge to re-encode the path segments.
Update your Terraform resource to remove the http_target section entirely:
resource "aws_cloudwatch_event_target" "test_api_gw_proxy_target" { arn = "${var.payment_processor_execution_arn}/devstage/POST/foo/events/ebevent" rule = aws_cloudwatch_event_rule.test_rule.name event_bus_name = aws_cloudwatch_event_bus.test_bus.name # Removed the http_target block—ARN already specifies the full path }
After applying this change, EventBridge will send requests directly to the path defined in the ARN without encoding slashes, so your ECS service will receive the original foo/events/ebevent path that matches your existing routes.
2. Verify API Gateway Integration Settings (Optional but Critical)
Double-check your API Gateway HTTP_PROXY integration to ensure it's configured to pass the path correctly:
- Confirm the integration request path is set to
{proxy}(matching your/foo/{proxy+}API path) - Ensure the HTTP method in the integration matches the
POSTmethod specified in your EventBridge target ARN - Verify there are no custom encoding/decoding rules in the API Gateway stage or integration settings that might interfere
3. Fallback: Use API Gateway Mapping Templates (If Needed)
If for some reason you can't remove the http_target block, you can add a mapping template in API Gateway to decode the encoded path before it reaches your ECS service:
- In your API Gateway stage settings, enable mapping templates
- Create a new
application/jsonmapping template with this content:{ "path": "$util.urlDecode($context.request.path)" } - Attach this template to your API's integration request to override the path parameter with the decoded version.
This approach only modifies API Gateway configuration, which has a much smaller blast radius than changing your ECS service routes.
内容的提问来源于stack exchange,提问作者annoyed_developer_2022

