How can I make my nextjs with Express site work on ssl

Viewed 4224

We have a site running on Next.js and Express. This is on a cPanel server with Aapche and together with nginx serving as reverse proxy.

I need to have ssl on the site. But I am quite confuused with how the configurations should be.

My server.js :

const express = require('express')
const next = require('next')
const https = require('https');
const fs = require('fs');
//const forceSSL = require('express-force-ssl')

var ssl_options = {
 key: fs.readFileSync('/home/myreactsite.key'),
 cert: fs.readFileSync('/home/myreactsite.crt'),
};

const dev = process.env.NODE_ENV !== 'production'
const app = next({ dev })
const handle = app.getRequestHandler()

const favicon = require('serve-favicon')
const path = require('path')

app.prepare()
.then(() => {
 const server = express()
 server.use(favicon(path.join(__dirname, 'static', 'images', 'favicon.ico')))

 server.get('*', (req, res) => {
  return handle(req, res)
})

server.listen(3007, (err) => {
   if (err) throw err
   console.log('> Ready on http://localhost:3007')
 })

var httpsServer = https.createServer(ssl_options,server).listen('8445', (err) => {
  if (err) throw err
  console.log('> Ready on https://localhost:8445')
})
})
.catch((ex) => {
 console.error(ex.stack)
 process.exit(1)
})

Apache runs on 8080 Nginx runs on 80 Next.js runs on both 3007 and 8445(I prefer it for ssl)

My Apache config contains the following to hide the port 3007

<Proxy *>
   Order deny,allow
   Allow from all
</Proxy>
ProxyPass / http://myreactsite.com:3007/

The site works fine if I access it as http://myreactsite.com . But it fails when I access https://myreactsite.com though I can access https version by specifying the port number as https://myreactsite.com:8445

I want to make it work without specifying the https port.

How can I get my site to force all pages to https without specifying the port?

2 Answers
Related