Google App Engine - Redirect HTTP to HTTPS

前端 未结 1 1545
执笔经年
执笔经年 2021-01-14 20:56

I\'m new to app engine and I\'m trying to set it up so that any http requests get redirected to https.

My app.yaml file looks like this. I have script: None in there

1条回答
  •  北荒
    北荒 (楼主)
    2021-01-14 21:39

    Use helmet, secure setting under handlers in app.yaml is depricated in the Google App Engine Latest Release.

    https://helmetjs.github.io/docs/hsts/

    https://expressjs.com/en/advanced/best-practice-security.html

    // Forcing HTTPS connections on Gooogle App Engine Flexible Environment sample app.js
    
    'use strict';
    
    const express = require('express');
    const helmet = require('helmet');
    
    const app = express();
    const port = process.env.PORT || 8080;
    
    app.disable('x-powered-by');
    
    app.enable('trust proxy');
    
    app.use(helmet.hsts({
        maxAge: 31536000,
        includeSubDomains: true,
        preload: true,
        setIf: function (req, res) {
            return req.secure;
        }
    }));
    
    app.get('/', (req, res) => {
        if (!req.secure) {
            res.redirect(301, "https://" + req.headers.host + req.originalUrl);
        }
        res.status(200).send("hello, world\n").end();
    });
    
    app.listen(port, () => {
        console.log(`App listening on port ${port}`);
        console.log('Press Ctrl+C to quit.');
    });
    

    Upgrading to the App Engine Latest Release

    The secure setting under handlers is now deprecated for the App Engine flexible environment. If you need SSL redirection, you can update your application code and use the X-Forwarded-Proto header to redirect http traffic.

    https://cloud.google.com/appengine/docs/flexible/php/upgrading#appyaml_changes

    Forcing HTTPS connections

    For security reasons, all applications should encourage clients to connect over https. You can use the Strict-Transport-Security header to instruct the browser to prefer https over http for a given page or an entire domain, for example:

    Strict-Transport-Security: max-age=31536000; includeSubDomains

    https://cloud.google.com/appengine/docs/flexible/php/how-requests-are-handled

    HTTPS and forwarding proxies

    With Express.js, use the trust proxy setting

    app.set('trust proxy', true);

    https://cloud.google.com/appengine/docs/flexible/nodejs/runtime#https_and_forwarding_proxies

    0 讨论(0)
提交回复
热议问题