How to permanently redirect `http://` and `www.` U

2019-03-14 10:13发布

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://www.mysite.xxx and just the naked domain mysite.xxx.

Is it possible to permanently redirect the last two to always use the secure https:// domain using the developers console or do I just have to redirect in the code?

5条回答
Melony?
2楼-- · 2019-03-14 10:57

Just in case, it is not possible to include secure handlers in app.yaml on App Engine Flexible, there isn't support for them:

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. (Reference: https://cloud.google.com/appengine/docs/flexible/java/upgrading#appyaml_changes)

The reference is from Java, but it seems to be the same for Node. I've tried to include handlers and it didn't work.

As you can see, a possible solution would be to "use X-Forwarded-Proto header to redirect http traffic". I haven't tried this because I will move to App Engine Standard, but someone has done it and explained here.

查看更多
够拽才男人
3楼-- · 2019-03-14 10:58

For the sake of completeness. The Java way is to set the transport guarantee to confidential like this.

<security-constraint>
  <web-resource-collection>
    <web-resource-name>profile</web-resource-name>
    <url-pattern>/profile/*</url-pattern>
  </web-resource-collection>
  <user-data-constraint>
    <transport-guarantee>CONFIDENTIAL</transport-guarantee>
  </user-data-constraint>
</security-constraint>

You can also find this here in the documentation.

查看更多
该账号已被封号
4楼-- · 2019-03-14 11:00

(For Node at least,) in your app.yaml, add the following:

handlers:
- url: /.*
  secure: always
  redirect_http_response_code: 301
  script: auto

Reference: https://cloud.google.com/appengine/docs/standard/nodejs/config/appref

查看更多
倾城 Initia
6楼-- · 2019-03-14 11:07

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
});
查看更多
登录 后发表回答