【问题标题】:How to handle 400 error in Nginx when redirect HTTP to HTTPS将HTTP重定向到HTTPS时如何处理Nginx中的400错误
【发布时间】:2015-02-03 21:25:54
【问题描述】:

我拥有一个网站,例如 HTTP 的 example.com。考虑到安全的东西,现在我想将 HTTP 更改为 HTTPS。我希望所有老客户即使使用 example.com 仍然可以访问我的网站,example.com 将通过 Nginx 重定向到 https。

当然,我google了很多,那么我的解决方法是:

upstream www {
  server 127.0.0.1:4000;
}
server {
  listen      80;
  listen      443 ssl;
  server_name localhost www example.com;

  ssl on;
  ssl_certificate  /usr/local/etc/docs/example.crt;
  ssl_certificate_key  /usr/local/etc/docs/example.key;

  if ($ssl_protocol = "") {
    rewrite ^ https://$host$request_uri? permanent;
  }

  # below are some other stuff
  # ...
}

但是当我访问 example.com 时,我得到了:

400 Bad Request 普通 HTTP 请求被发送到 HTTPS 端口

然后我在阅读Redirect in nginx之后更改了nginx.conf,并将error_page配置为497:

upstream www {
  server 127.0.0.1:4000;
}
server {
  listen      80;
  listen      443 ssl;
  server_name localhost www example.com;

  ssl on;
  ssl_certificate  /usr/local/etc/docs/example.crt;
  ssl_certificate_key  /usr/local/etc/docs/example.key;

  error_page 497  https://$host$request_uri;

  # below are some other stuff
  # ...
}

然后它工作,一切都很好。但我只是不知道为什么,error_page 的解决方案似乎很奇怪。所以 阅读Dealing with nginx 400 “The plain HTTP request was sent to HTTPS port” error后,我添加了默认并删除了ssl。

upstream www {
  server 127.0.0.1:4000;
}
server {
  listen      80;
  listen      443 default ssl;
  server_name localhost www example.com;

  ssl on;
  ssl_certificate  /usr/local/etc/docs/example.crt;
  ssl_certificate_key  /usr/local/etc/docs/example.key;

  if ($ssl_protocol = "") {
    rewrite ^ https://$host$request_uri? permanent;
  }

  # below are some other stuff
  # ...
}

太棒了!它再次起作用。但我不确定:

  • 哪种解决方案是正确的?
  • 如果两者都正确,哪个对SEO更友好?

【问题讨论】:

    标签: http redirect ssl nginx https


    【解决方案1】:

    解决方案一是真连线,从http://moz.com/learn/seo/redirection,可以发现永久重定向更友好。

    server {
        listen 80;
        server_name www.example.com;
        return 301 https://$host$request_uri;
    }
    
    
    server {
    
      listen      443 default ssl;
      server_name  www example.com;
    
      ssl on;
      ssl_certificate  /usr/local/etc/docs/example.crt;
      ssl_certificate_key  /usr/local/etc/docs/example.key;
    
    
    
      # below are some other stuff
      # ...
    }
    

    【讨论】:

      猜你喜欢
      • 2016-04-11
      • 2022-08-14
      • 1970-01-01
      • 2011-03-29
      • 2018-01-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多