Last active
September 14, 2021 11:36
-
-
Save jordanmaslyn/71dcff70853daadee079d6b482dc7880 to your computer and use it in GitHub Desktop.
Use NextJS custom server for apex domain to www redirects
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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