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

3

有没有办法将我的Web应用程序更改为在HTTPS上进行监听,而不是HTTP呢?我正在使用node.js/express。

我需要它在HTTPS上进行监听,因为我正在使用地理定位,Chrome不再支持除HTTPS之外的安全环境中提供的服务。

这是当前的'./bin/www'文件,它目前正在HTTP上进行监听。

#!/usr/bin/env node

var app = require('../app');
var debug = require('debug')('myapp:server');
var http = require('http');

var port = normalizePort(process.env.PORT || '9494');
app.set('port', port);


var server = http.createServer(app)

server.listen(port);
server.on('error', onError);
server.on('listening', onListening);


function normalizePort(val) {
  var port = parseInt(val, 10);

  if (isNaN(port)) {
    // named pipe
    return val;
  }

  if (port >= 0) {
    // port number
    return port;
  }

  return false;
}

function onError(error) {
  if (error.syscall !== 'listen') {
    throw error;
  }

  var bind = typeof port === 'string'
    ? 'Pipe ' + port
    : 'Port ' + port;

  // handle specific listen errors with friendly messages
  switch (error.code) {
    case 'EACCES':
      console.error(bind + ' requires elevated privileges');
      process.exit(1);
      break;
    case 'EADDRINUSE':
      console.error(bind + ' is already in use');
      process.exit(1);
      break;
    default:
      throw error;
  }
}


function onListening() {
  var addr = server.address();
  var bind = typeof addr === 'string'
    ? 'pipe ' + addr
    : 'port ' + addr.port;
  debug('Listening on ' + bind);
}

你好,欢迎来到Stack Overflow!通常情况下,如果您包括您已经尝试过什么以及它如何不适合您的需求,这有助于获得答案。 - William Patton
1个回答

4

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

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

然后,通过Node的HTTPS库以HTTPS方式提供服务:

// 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服务器来监听来自相同域的请求并将它们重定向:
// 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端口等。

相关阅读:


非常好的答案!我稍微修改了一下代码,所以重定向到 'https://localhost'+req.originalUrl,这样客户端就会被重定向到他想要访问的网站。 - kaiya
你可能不想使用80和443端口,为什么? - sander
1
@sander 通常最好的做法是让您的服务监听私有端口,如8080,并使用像nginx这样的工具来处理HTTPS和重定向到正确的服务。这样,您可以将部署与代码解耦,可以在生产环境、本地环境和docker内重复使用相同的代码等。当然,这取决于上下文。 - Nino Filiu

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接