将非www和HTTP重定向到www和HTTPS

时间:2019-02-11 15:23:57

标签: node.js express redirect dns url-redirection

我正在运行Express Web服务器。我使用Let's Encypt为我的域的www版本和非www版本创建SSL证书。我的DNS有以下记录:

CNAME | Host: @   | Target: dynamicdns.example.com. | TTL: 60min
CNAME | Host: www | Target: dynamicdns.example.com. | TTL: 60min

我也有以下node.js代码来运行Web服务器:

// Dependencies
const express = require('express');
const fs = require('fs');
const http = require('http');
const https = require('https');

// Create express instance
const app = express();

// Get credentials from system
const privateKey = fs.readFileSync('/etc/letsencrypt/live/www.example.com/privkey.pem', 'utf8');
const certificate = fs.readFileSync('/etc/letsencrypt/live/www.example.com/cert.pem', 'utf8');
const ca = fs.readFileSync('/etc/letsencrypt/live/www.example.com/chain.pem', 'utf8');
const credentials = {
    key: privateKey,
    cert: certificate,
    ca: ca
};

// Initalize server
app.use(express.static('public'));
const httpServer = http.createServer(app);
const httpsServer = https.createServer(credentials, app);

// Listen for HTTP
httpServer.listen(80, () => {
    console.log('HTTP Server running on port 80');
});

// Listen for HTTPS
httpsServer.listen(443, () => {
    console.log('HTTPS Server running on port 443');
});

这一切都可以正常工作,但是会产生一个问题,即对于同一内容具有多个有效URL。现在,以下URL均有效:

http://example.com
http://www.example.com
https://example.com
https://www.example.com

我想将所有错误的URL重定向到https://www.example.com,这是正确的URL。我不确定该怎么做。任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:0)

您可以使用像这样的中间件来检查所有域并进行相应的重定向:

app.use((req, res, next) => {
  if (!req.secure) {
    return res.redirect('https://' + req.get('host') + req.url);
  }
  next()
})

只需确保仅将其用于生产