且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用node.js/Express从HTTP重定向到HTTPS

更新时间:2022-04-10 22:57:02

是的,有一种方法.首先,生成一个自签名证书:

Yes, there is a way. First off, generate a self-signed certificate:

openssl req -nodes -new -x509 -keyout server.key -out server.cert

然后,借助Node的HTTPS库,通过HTTPS提供服务:

Then, serve over HTTPS thanks to Node's HTTPS lib:

// imports
const express = require('express');
var fs = require('fs');
const http = require('http');
const https = require('https');
const app = require('./path/to/your/express/app');

// HTTPS server
const httpsServer = https.createServer({
    key: fs.readFileSync('server.key'),
    cert: fs.readFileSync('server.cert')
}, app);
httpsServer.listen(443, () => console.log(`HTTPS server listening: https://localhost`));

最后,使用最小的HTTP服务器来侦听到相同域的请求并将其重定向:

Finally, use a minimal HTTP server to listen requests to the same domain and redirects them:

// redirect HTTP server
const httpApp = express();
httpApp.all('*', (req, res) => res.redirect(300, 'https://localhost'));
const httpServer = http.createServer(httpApp);
httpServer.listen(80, () => console.log(`HTTP server listening: http://localhost`));

当然,这是最小设置.对于生产,您将使用不同的证书,并将localhost替换为将从req生成的动态域名,并且您可能不想使用端口80和443等.

This is, of course, the minimal setup. For production, you'll use different certificates, and replace localhost by a dynamic domain name that you'll generate from req, and you might not want to use the ports 80 and 443, etc.

相关阅读:

  • Express + HTTPS
  • Express::res.redirect()
  • Redirecting to HTTPS in Express
  • HTTPS when deploying with Heroku