【问题标题】:How to redirect a nextjs app hosted on Heroku from http to https?如何将托管在 Heroku 上的 nextjs 应用程序从 http 重定向到 https?
【发布时间】:2020-03-19 07:30:56
【问题描述】:

我在 Heroku 上托管了一个 nextjs 应用程序。该应用没有自定义服务器,直接访问 https 网址即可。

但是,如果用户直接访问 http URL,我想将他们重定向到 https 页面。

如今实现这一目标的最佳方法是什么?

here提到了一个非常hacky的解决方案,但我感觉有更好的解决方案。

有什么想法吗?

【问题讨论】:

  • 为什么不用nginx反向代理服务器?

标签: redirect heroku https next.js


【解决方案1】:

您可以使用Edge addon in Heroku,它将 CloudFront CDN 放置在可以处理重定向的应用程序前面。这会强制执行 HTTPS,即 Edge 自动将 HTTP 请求重定向到 HTTPS。

来源: https://elements.heroku.com/addons/edge

【讨论】:

    【解决方案2】:

    如果你不需要插件,你可以使用heroku-community/nginx buildpack 和一个自定义的 nginx 配置来强制使用 HTTPS:

    http {
      server {
        listen <%= ENV["PORT"] %>;
        server_name _;
        keepalive_timeout 5;
    
        location / {
    
          <% if ENV['NGINX_SKIP_HTTPS_PROXY'] == 'true' %>
            if ($http_x_forwarded_proto != "https") {
              return 301 https://$host$request_uri;
            }
          <% end %>
    
          proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
          proxy_set_header Host $http_host;
          proxy_redirect off;
          proxy_pass http://localhost:3000; #next serve listens here and receives nginx requests
        }
      }
    }
    

    您可以在this post 中找到完整的配置详细信息。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-11-06
      • 2021-08-31
      • 2014-08-20
      • 2013-02-13
      • 2017-05-16
      • 1970-01-01
      • 2018-05-12
      • 2018-07-30
      相关资源
      最近更新 更多