简体   繁体   中英

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

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM