如何将托管在 Heroku 上的 nextjs 应用程序从 http 重定向到 https?

How to redirect a nextjs app hosted on Heroku from http to https?

我在 Heroku 上托管了一个 nextjs 应用程序。该应用程序没有自定义服务器,直接访问 https URL 可以正常工作。

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

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

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

有什么想法吗?

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

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

如果您不需要插件,您可以使用 heroku-community/nginx 带有自定义 nginx 配置的 buildpack,强制使用 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 中找到完整的配置详细信息。