S3 Static website hosting: Is it possible to add m

2019-07-23 19:14发布

问题:

I am currently hosting a static website on S3 which is using redirection rules to re-route the request to a lambda function.

The problem is I have two buckets that are both acting as static websites (sandbox vs production) and I need to be able to point them to the same lambda function but be able to tell them apart when the function is run. Whether it's a header, a GET parameter, string manipulation, anything I can use to determine which bucket the request came from.

Does anyknow know how inside the lambda function I can identify that the request came from one bucket over the other? This is the current redirect rules I am using:

<RoutingRules>
  <RoutingRule>
    <Condition>
      <KeyPrefixEquals/>
     <HttpErrorCodeReturnedEquals>404</HttpErrorCodeReturnedEquals>
    </Condition>
    <Redirect>
      <Protocol>https</Protocol>
      <HostName>removed.execute-api.us-east-2.amazonaws.com</HostName>
      <ReplaceKeyPrefixWith>prod/func?key=</ReplaceKeyPrefixWith>
      <HttpRedirectCode>307</HttpRedirectCode>
    </Redirect>
  </RoutingRule>
</RoutingRules>

From what I understand I cannot set and headers or GET parameters from this routing ruleset as the validation for the rules fails and my only option as it stands is to duplicate the lambda function, which I really don't want to do as it feels verbose.

I have also done JSON.stringify() on the event & context parameters within the Lambda function and cannot seem to see any item to help me uniquely identify the origin bucket.

Appreciate any help with this.

回答1:

If you want to add query string ("GET") parameters, you have to remember that this is an XML document, which requires escaping &&amp;. S3 will still render the query string correctly in the redirect with this approach.

Invalid:

<ReplaceKeyPrefixWith>prod/func?foo=bar&buzz=fizz&key=</ReplaceKeyPrefixWith>

Valid:

<ReplaceKeyPrefixWith>prod/func?foo=bar&amp;buzz=fizz&amp;key=</ReplaceKeyPrefixWith>