【问题标题】:Redirect non-www and HTTP to www and HTTPS将非 www 和 HTTP 重定向到 www 和 HTTPS
【发布时间】:2019-02-11 15:23:57
【问题描述】:

我正在运行 Express 网络服务器。我使用 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 代码来运行网络服务器:

// 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。以下网址现在都有效:

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

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

【问题讨论】:

  • 我强烈建议您考虑使用反向代理,例如 Nginx。

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


【解决方案1】:

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

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

请确保仅将其用于生产

【讨论】:

  • 这不会从非 www 切换到 www
  • 只需在下一个 if 之前添加另一个以检查 www 部分并相应地重定向 ``` if ( req.get('host').search(/^www/) !== -1 ) { return res.redirect('example.com' + req.url); } ```
  • @JulianLachniet 我的回答够清楚还是您还有疑问?另外...顶部评论中的建议非常有效,为了获得更好的性能,您希望在顶部放置一个 Nginx 来处理 SSL 并重定向到正确的域,而不是让 Node 这样做,这里有一些文章这可以帮助你:sitepoint.com/configuring-nginx-ssl-node-js
猜你喜欢
  • 2018-09-26
  • 1970-01-01
  • 2015-05-01
  • 2012-05-30
  • 2015-04-20
  • 2017-09-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多