Skip to content

Instantly share code, notes, and snippets.

@jordanmaslyn
Last active September 14, 2021 11:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jordanmaslyn/71dcff70853daadee079d6b482dc7880 to your computer and use it in GitHub Desktop.
Save jordanmaslyn/71dcff70853daadee079d6b482dc7880 to your computer and use it in GitHub Desktop.
Use NextJS custom server for apex domain to www redirects
const { createServer } = require('http');
const { parse } = require('url');
const next = require('next');
const dev = process.env.NODE_ENV !== 'production';
const app = next({ dev });
const handle = app.getRequestHandler();
const port = process.env.APP_PORT || 8080;
app.prepare().then(() => {
createServer((req, res) => {
const parsedUrl = parse(req.url, true);
if (req.headers.host?.indexOf('example.com') === 0) {
res.writeHead(301, {
Location: 'https://www.example.com' + req.url,
});
res.end();
} else {
handle(req, res, parsedUrl);
}
}).listen(port, err => {
if (err) throw err;
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment