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

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

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

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

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

有什么想法吗?

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

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

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

,

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

本文链接:https://www.f2er.com/3045890.html

大家都在问