【发布时间】: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