0

I have a series of serverless next.js apps running on AWS that I am serving at subdomains, and I want to proxy them to subdirectories on my main domain. So, for example, the app at foo.example.com/foo/ should appear at www.example.com/foo/.

I've accomplished this by using http-proxy and express. I have a fairly simple express server that runs in its own serverless app, like so:

const serverless = require('serverless-http');
const httpProxy = require('http-proxy');
const express = require('express');
const app = express();

const proxy = httpProxy.createProxyServer();

app.get('/', (req, res) => {
  res.send('Hello, you are at index.');
});

app.get('/:project/*', (req, res) => {
  const project = req.params.project;
  const rest = req.params[0];
  const url = `https://${project}.example.com/${project}/`;

  req.url = `/${rest}`;
  req.headers['X-Projects-Router-Proxy'] = true;
  req.body = undefined;

  proxy.web(req, res, {
    target: url,
    xfwd: false,
    toProxy: true,
    changeOrigin: true,
    secure: true,
  });
});

module.exports.handler = serverless(app);

This works quite well on its own, which is great. However, when I try to put this behind CloudFront, the index page works fine, but anything that touches the proxy returns a 403 error:

403 ERROR
The request could not be satisfied.
Bad request. 
Generated by cloudfront (CloudFront)

What might be going wrong here, and how can I configure http-proxy so that it will cooperate with CloudFront?

futuraprime
  • 5,468
  • 7
  • 38
  • 58

1 Answers1

1

You need to add *.example.com into CloudFront CNAME/Alternative name filed and also in DNS to point it to CloudFront, when url changes as {project}.example.com, CloudFront finds the distribution based on the host header and if it can't find, it'll give you 403 error.

James Dean
  • 4,033
  • 1
  • 9
  • 18
  • Unfortunately, the domains are all already listed in the CNAME/Alternative name field. I am not sure what you mean about the host header—what is CloudFront expecting there? – futuraprime Aug 01 '19 at 10:46
  • 1
    cloudfront is expecting host header in the request should match with the alternate name added to it. – James Dean Aug 02 '19 at 06:50