Setting up AWS CloudFront as a reverse proxy

Last updated:

|Edit this page

CloudFront can be used as a reverse proxy. Although there are multiple other options if you're using AWS.

By default, CloudFront doesn't forward headers, cookies, or query parameters received from the origin that PostHog uses. To set these up, you need an "origin request policy" as in the instructions below.

Create a distribution

  1. On the AWS dashboard, search for CloudFront, then create a new CloudFront distribution
  2. Set the origin domain to your PostHog instance app.posthog.com or eu.posthog.com for PostHog Cloud).
  3. Select HTTPS only.
  4. Under Default cache behavior, go to Viewer. “Under Allowed HTTP methods,” select “GET, HEAD, OPTIONS, PUT, POST, PATCH, DELETE,” and check OPTIONS under “Cache HTTP methods.” This allows all HTTP methods.
  5. Under Cache policy, click “Create policy.” On the “Create cache policy” page:
    1. Name your policy “origin-cors.”
    2. Scroll to “Cache key settings,” click the dropdown for “Headers” that says “Include the following headers,” select Origin and Authorization.
    3. Under “Query strings,” select “All.”
    4. Click “Create” at bottom of the page.
a screenshot of the cloudfront cache policy settings
  1. Back on the “Create distribution” page, select your “origin-cors” cache policy.
  2. Under “Origin request policy,” choose “CORS-CustomOrigin.”
  3. Under “Response headers policy,” choose “CORS-with-preflight-and-SecurityHeadersPolicy.”
  4. Do not enable AWS Web Application Firewall (WAF).
  5. Click “Create distribution” at bottom of the page.

Once created, copy the distribution domain name, and set it as your API host in your PostHog initialization like this:

JavaScript
posthog.init('<ph_project_api_key>',
{
api_host: 'https://<distribution_domain_name>.cloudfront.net',
}
)

You can find out about CloudFront pricing on the AWS website.

Setup video

Questions?

Was this page useful?

Next article

Using Next.js rewrites as a reverse proxy

If you are using Next.js, you can take advantage of rewrites to behave like a reverse proxy. To do so, add a rewrites() function to your next.config.js file: Then configure the PostHog client to send requests via your rewrite. If this isn't working for you (returning 503 errors), it may be an issue with how your hosting service (such as Heroku) handles rewrites. You can write Next.js middleware to proxy requests instead. Setup video

Read next article