Symfony, AWS Lambda, APIGateway and custom domains with paths
Fabian Blechschmidt
We are currently developing an API to enrich PDF invoices with XML data called Zugferd.
AWS API Gateway and custom paths
We are hosting it on AWS Lambda to have it scalable and easy to maintain. One of the things we had to configure is to make it available under one of our domains, because no one wants a domain like https://2d0gb7hlaa.execute-api.eu-central-1.amazonaws.com/ so one can configure an own domain under API Gateway, one can find it under:
Once the domain is configured, you can set mappings for your different stages:
This means, in our example we ended up with something like:
example.com/test ? development API
example.com/stage ? stage API
example.com/ ? production API
Woho! The right procotoll (HTTPS)
And this worked perfectly fine in the beginning, then we introduced AWS Cognito into the mix and ended up with broken redirects (the httpS was missing and the path with missing, so I assumed that the base_url isn’t determined correctly). I read the bref.sh documentation about proxies but it didn’t help on this issue. The Symfony documentation was better, I setup the configuration in framework.yaml and magically https appeared, but the path was still wrong.
Add the prefix to the headers
I searched the net to tell AWS Lambda or the API Gateway to add the X-Forwarded-Prefix, but couldn’t find an automatic way or a configuration. Then I wanted it to be added „manually“ but at least use the configured path of the AWS API Gateway configuration (we talked above about), but even for that I didn’t find a variable in the configuration. So we do it „hardcoded“.
Here is, how you do it:
Go into the route details, click on „Configure“
On the bottom right you find „Parameter mapping“, click on „Create“
Add the following settings:
Mapping Type: All incoming requests
Parameter to modify: header.X-Forwarded-Prefix
Modification type: overwrite
Value: whatever your path is, in my case: „/stage/“
Click on Save
Finally the right path
And with these settings and the framework.yaml appended with X-Forwarded-Prefix, we finally get a correct generated URL.
And for reference, here the important part of our framework.yaml file:
when@prod:
framework:
# trust the remote address because API Gateway has no fixed IP or CIDR range that we can target
trusted_proxies: '127.0.0.1'
# trust "X-Forwarded-*" headers coming from API Gateway
trusted_headers: [ 'x-forwarded-for', 'x-forwarded-proto', 'x-forwarded-port', 'x-forwarded-prefix' ]
I hope this helps and good luck with your AWS journey!