Search code examples
amazon-s3amazon-ec2amazon-cloudfront

Getting 405 error code when using Cloudfront to origin on ec2 instance


I created a cloudfront distribution that connected to 2 origins: 1. s3 static website I uploaded. 2. ec2 instance with nginx docker with the following configuration:

location /api {
        proxy_pass http://my_app:8080;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
  }
  client_max_body_size 1000M;
  server_tokens off;

I configure 2 behaviors s3 with Default (*) path pattern allowing all HTTP methods use origin cache headers. forward all caching and string.

ec2 path pattern api allowing all HTTP methods use origin cache headers. forward all caching and string.

and I'm getting 405

<html>
<head><title>405 Method Not Allowed</title></head>
<body>
<h1>405 Method Not Allowed</h1>
<ul>
<li>Code: MethodNotAllowed</li>
<li>Message: The specified method is not allowed against this resource.</li>
<li>Method: POST</li>
<li>ResourceType: OBJECT</li>
<li>RequestId: 871316565A038A65</li>
<li>HostId: BHbdP09UWX2xCvW6qqpOQYaGwy4lvgrVVYoSCaLrSBZ2TALZT5kk9Po7k6Akq2FYZ6NojFyINBk=</li>
</ul>
<hr/>
</body>
</html>

Solution

  • The response is coming from S3 as you can see RequestId and HostId in the response. S3 supports POST http request but you need to make sure that it has Form-Data. S3 with POST request only accept Form data. https://docs.aws.amazon.com/AmazonS3/latest/API/RESTObjectPOST.html

    If you can't use Form-data, use PUT request to CloudFront.