Explain the correct way to redirect nginx server http to https

  • 2020-05-13 04:30:58
  • OfStack

http redirects to https using nginx's redirect command. So how do you write a redirect? Previous versions of nginx might have used a similar format.


rewrite ^/(.*)$ http://domain.com/$1 permanent;

or


rewrite ^ http://domain.com$request_uri? permanent;

Now that the new version of nginx has been written in a different way, these are no longer recommended.

Here's how the nginx http page redirects to the https page:


server {
  listen   80;
  server_name  my.domain.com;
  return   301 https://$server_name$request_uri;
}

server {
  listen   443 ssl;
  server_name  my.domain.com;

  [....]
}

Related articles: