Express SSL 重定向不适用于 root /
Express SSL redirect not working for root /
我在 Express 路由声明的末尾使用通配符匹配来测试连接是否不是 HTTPS,如果不是,则重定向到 URI 的 HTTPS 版本。
这适用于除 root 之外的所有内容,即 www.domain.com。这有点问题,因为 domain.com 服务于 SPA。
app.get('*', function (req, res) {
if (req.headers['X-forwarded-proto'] != 'https') {
res.redirect('https://domain.com/#' + url_path);
}
else {
res.redirect('/#' + url_path);
}
});
我注意到当 URL 是根域时,甚至不会调用这段代码。我想这可能是因为我也声明:
app.use(express.static(path.join(application_root, 'public')));
这是 SPA 为所有资产提供服务所必需的。当我删除此行时,现在会为根域调用我的路由处理程序,但我的主页现在会无限重定向。
我必须创建一个自定义路由来为我的 SPA 文件提供服务,重命名 index.html 这样 Express 就不会尝试服务它而不是我的路由。
对于可能仍在为此苦苦挣扎的任何人,我在 Heroku 上部署我的 React-Express 应用程序时遇到了同样的问题。我使用了一个中间件:“heroku-ssl-redirect”。我的解决方案是将这个中间件放在层次结构中(现在它是我应用的第一个中间件):
var sslRedirect = require("heroku-ssl-redirect");
const express = require('express');
const path = require('path');
const e = require('express');
const app = express();
app.use(sslRedirect());
// Serve the static files from the React app
app.use(express.static(path.join(__dirname, 'client/build')));
// Handles any requests that don't match the ones above
app.get('*', (req, res) =>{
res.sendFile(path.join(__dirname+'/client/build/index.html'));
});
const port = process.env.PORT || 5000;
app.listen(port);
console.log('App is listening on port ' + port);
我在 Express 路由声明的末尾使用通配符匹配来测试连接是否不是 HTTPS,如果不是,则重定向到 URI 的 HTTPS 版本。
这适用于除 root 之外的所有内容,即 www.domain.com。这有点问题,因为 domain.com 服务于 SPA。
app.get('*', function (req, res) {
if (req.headers['X-forwarded-proto'] != 'https') {
res.redirect('https://domain.com/#' + url_path);
}
else {
res.redirect('/#' + url_path);
}
});
我注意到当 URL 是根域时,甚至不会调用这段代码。我想这可能是因为我也声明:
app.use(express.static(path.join(application_root, 'public')));
这是 SPA 为所有资产提供服务所必需的。当我删除此行时,现在会为根域调用我的路由处理程序,但我的主页现在会无限重定向。
我必须创建一个自定义路由来为我的 SPA 文件提供服务,重命名 index.html 这样 Express 就不会尝试服务它而不是我的路由。
对于可能仍在为此苦苦挣扎的任何人,我在 Heroku 上部署我的 React-Express 应用程序时遇到了同样的问题。我使用了一个中间件:“heroku-ssl-redirect”。我的解决方案是将这个中间件放在层次结构中(现在它是我应用的第一个中间件):
var sslRedirect = require("heroku-ssl-redirect");
const express = require('express');
const path = require('path');
const e = require('express');
const app = express();
app.use(sslRedirect());
// Serve the static files from the React app
app.use(express.static(path.join(__dirname, 'client/build')));
// Handles any requests that don't match the ones above
app.get('*', (req, res) =>{
res.sendFile(path.join(__dirname+'/client/build/index.html'));
});
const port = process.env.PORT || 5000;
app.listen(port);
console.log('App is listening on port ' + port);