How to handle 400 error in Nginx when redirect HTTP to HTTPS

坚强是说给别人听的谎言 提交于 2020-01-02 08:45:28

问题


I own a website, like example.com by HTTP. Considering the secure stuff, now I want to change the HTTP to HTTPS. And I hope all the old customers could still be able to visit my website even they use example.com which will be redirect to https via Nginx.

Of course, I googled a lot, then my solution is:

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
  # ...
}

But when I visit example.com, I got:

400 Bad Request The plain HTTP request was sent to HTTPS port

Then I change the nginx.conf, after reading Redirect in nginx , and config the error_page by 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
  # ...
}

Then it works, everything is fine. But I just don't know why and the solution of error_page just seems werid. So after reading Dealing with nginx 400 “The plain HTTP request was sent to HTTPS port” error, I add the default and remove the ssl on.

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
  # ...
}

Great! It works again. But I am not for sure:

  • Which solution is correct?
  • If both correct, which is more friendly for SEO?

回答1:


Solution 1st is really wired, from http://moz.com/learn/seo/redirection, can find that permanent redirection is more friendly.

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
  # ...
}


来源:https://stackoverflow.com/questions/27320460/how-to-handle-400-error-in-nginx-when-redirect-http-to-https

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!