How to handle 400 error in Nginx when redirect HTT

2019-05-14 15:47发布

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条回答
劫难
2楼-- · 2019-05-14 16:30

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
  # ...
}
查看更多
登录 后发表回答