【问题标题】:Nginx how to redirect http to https?Nginx如何将http重定向到https?
【发布时间】:2022-08-14 15:37:52
【问题描述】:

我是 aws 服务和 nginx 配置的新手。 我正在使用 nginx,我的 EB 实例是单个实例,前面有经典模式的负载均衡器。

我在系统中有这个配置文件:

      server {
        listen 80;
        server_name _;
        return 301 https://$host$request_uri;
      }

      server {
        listen 8080;

        if ($time_iso8601 ~ \"^(\\d{4})-(\\d{2})-(\\d{2})T(\\d{2})\") {
            set $year $1;
            set $month $2;
            set $day $3;
            set $hour $4;
        }
        access_log /var/log/nginx/healthd/application.log.$year-$month-$day-$hour healthd;
        access_log  /var/log/nginx/access.log  main;

        location / {
            proxy_pass  http://nodejs;
            proxy_set_header   Connection \"\";
            proxy_http_version 1.1;
            proxy_set_header        Host            $host;
            proxy_set_header        X-Real-IP       $remote_addr;
            proxy_set_header        X-Forwarded-For $proxy_add_x_forwarded_for;
        }

该机器位于 aws elastic beanstack 和 EC2 的负载均衡器后面,根据 aws docs 已经配置为从 80 重定向到 443 https://aws.amazon.com/premiumsupport/knowledge-center/elb-redirect-http-to-https-using-alb/

这里的问题是从 http 到 https 的重定向不起作用,当我从 http 到 https 时,我无法访问我的网站。

当我访问我的网站http://something.com 然后刷新它时,奇怪的场景会根据我的意愿重定向到https://something.com,但不是立即。 任何建议如何解决这个问题?

*http 和 https 访问都可以正常工作,但我希望从 http 访问的所有客户端都将它们重定向到 https。

  • @Richard Smith,哦,对不起,当我检查时我没有更新这个原始文件,在我的配置文件中就像你说的那样,所以我不认为这是我的问题。我会更新问题
  • 尝试这些通常推荐的重定向之一,而不是使用 $host 变量:return 301 https://example.com$request_uri;return 301 https://$server_name$request_uri;
  • @Bman70 我确实部署了你的两个答案,但它没有工作
  • 你的服务器在哪里监听 443 ssl?它会重定向,但我没有看到它在监听 ssl 重定向请求。我也没有看到 default_server 块。这里有一些很好的例子(没有太多接受的答案,但其他一些):serverfault.com/questions/250476/…
  • @Bman70 谢谢我会调查它,我会尝试这些答案或组合其中一些:)

标签: nginx amazon-ec2 amazon-elastic-beanstalk nginx-config nginx-location


【解决方案1】:

我做了这个解决方案及其工作 node.js 端

app.use(function(req, res, next) {
  if (
    (!req.secure) && (req.get('X-Forwarded-Proto') !== 'https') &&
    !req.get('Host').includes('localhost')
  ) {
    res.redirect('https://' + req.get('Host') + req.url);
  }
  else next();
});

【讨论】:

  • 通过添加有关代码的作用以及它如何帮助 OP 的更多信息,可以改进您的答案。
猜你喜欢
  • 2011-03-29
  • 2018-01-05
  • 1970-01-01
  • 2014-10-11
  • 2018-08-18
  • 2017-02-25
  • 1970-01-01
  • 2011-04-23
  • 1970-01-01
相关资源
最近更新 更多