http - 将 HTTP 重定向到 HTTPS 时如何处理 Nginx 中的 400 错误

标签 http redirect ssl nginx https

我拥有一个网站,例如 HTTP 的 example.com。考虑到安全问题,现在我想将 HTTP 更改为 HTTPS。我希望所有的老客户仍然可以访问我的网站,即使他们使用 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 The plain HTTP request was sent to HTTPS port

然后我改变了nginx.conf,看完Redirect in nginx , 并通过 497 配置 error_page:

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 更友好?

最佳答案

解决方案 1st 确实有线,来自 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
  # ...
}

关于http - 将 HTTP 重定向到 HTTPS 时如何处理 Nginx 中的 400 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27320460/

相关文章:

javascript - http 请求与 ajax/angularjs 的命名约定 http 请求

javascript - Angularjs $http.get 方法不起作用

.htaccess - 子域通配符 htaccess 重定向到新域

python - Cloudscraper 返回 AttributeError : 'SSLContext' object has no attribute 'orig_wrap_socket'

c++ - LibCurl HTTPS 凭据,内部处理的序列?

java - 使用 keystore api 'unable to find valid certification path to requested target' 的内存 keystore

C++ POST 表单数据

HTTPS 与 HTTP 速度比较

c# - ASP.Net MVC - 有条件的未经授权的重定向

JSF 过滤器在初始重定向后不重定向