How to permanently redirect `http://` and `www.` URLs to `https://`?

后端 未结 6 1204
粉色の甜心
粉色の甜心 2020-12-24 11:34

I have a Google App Engine project. On this project I have setup a custom domain and an SSL certificate. Therefore, I can use https://www.mysite.xxx, http

6条回答
  •  难免孤独
    2020-12-24 12:08

    It should be done in your application. Please check this post https://stackoverflow.com/a/54289378/5293578

    I've tried the following code and it worked for me (You must put this before the default request and error handler):

    /**==== File: server.js =======**/
    
    /** Express configuration **/
    
    // HTTPS Redirection
    if (process.env.NODE_ENV === 'production') {
      app.use (function (req, res, next) {
        var schema = (req.headers['x-forwarded-proto'] || '').toLowerCase();
        if (schema === 'https') {
          next();
        } else {
          res.redirect('https://' + req.headers.host + req.url);
        }
      });
    }
    
    /** ... more configuration **/
    
    // Default request handler
    app.use(function(req, res, next) {
      // ... your code
    });
    
    // Default error handler
    app.use(function(err, req, res, next) {
      // ... your code
    });
    

提交回复
热议问题