help https behind proxy
This commit is contained in:
parent
e432d43376
commit
91e3050235
1
env.dist
1
env.dist
@ -14,4 +14,5 @@ DATABASE_URL=./water_stations.db
|
|||||||
|
|
||||||
# Server configuration
|
# Server configuration
|
||||||
PORT=3000
|
PORT=3000
|
||||||
|
# Set to true to force HTTPS redirects (works with reverse proxies)
|
||||||
FORCE_HTTPS=false
|
FORCE_HTTPS=false
|
27
server.js
27
server.js
@ -92,14 +92,24 @@ app.use(bodyParser.json());
|
|||||||
app.use(bodyParser.urlencoded({ extended: true }));
|
app.use(bodyParser.urlencoded({ extended: true }));
|
||||||
app.use(express.static(path.join(__dirname, 'public')));
|
app.use(express.static(path.join(__dirname, 'public')));
|
||||||
|
|
||||||
|
// Trust proxy headers (required for Apache/nginx reverse proxy setups)
|
||||||
|
app.set('trust proxy', true);
|
||||||
|
|
||||||
// HTTPS enforcement middleware
|
// HTTPS enforcement middleware
|
||||||
if (FORCE_HTTPS) {
|
if (FORCE_HTTPS) {
|
||||||
app.use((req, res, next) => {
|
app.use((req, res, next) => {
|
||||||
if (req.header('x-forwarded-proto') !== 'https') {
|
// Check if the original request was HTTP
|
||||||
res.redirect(`https://${req.header('host')}${req.url}`);
|
// req.secure will be true if the original request was HTTPS (when trust proxy is enabled)
|
||||||
} else {
|
// x-forwarded-proto header is set by the proxy
|
||||||
next();
|
const isHttps = req.secure || req.header('x-forwarded-proto') === 'https';
|
||||||
|
|
||||||
|
if (!isHttps) {
|
||||||
|
// Only redirect if the original client request was HTTP
|
||||||
|
const host = req.header('x-forwarded-host') || req.header('host');
|
||||||
|
return res.redirect(301, `https://${host}${req.url}`);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
next();
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -122,8 +132,13 @@ app.use(passport.session());
|
|||||||
|
|
||||||
// Helper function to get base URL
|
// Helper function to get base URL
|
||||||
function getBaseUrl(req) {
|
function getBaseUrl(req) {
|
||||||
const protocol = FORCE_HTTPS || req.secure || req.header('x-forwarded-proto') === 'https' ? 'https' : 'http';
|
// Determine protocol: use HTTPS if forced, or if original request was HTTPS
|
||||||
const host = req.header('host');
|
const isHttps = FORCE_HTTPS || req.secure || req.header('x-forwarded-proto') === 'https';
|
||||||
|
const protocol = isHttps ? 'https' : 'http';
|
||||||
|
|
||||||
|
// Use x-forwarded-host if available (set by proxy), otherwise use host header
|
||||||
|
const host = req.header('x-forwarded-host') || req.header('host');
|
||||||
|
|
||||||
return `${protocol}://${host}`;
|
return `${protocol}://${host}`;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
Loading…
x
Reference in New Issue
Block a user