1

I've seen two ways nginx is used to redirect http to https:

server {
  listen 80;
  listen [::]:80;
  server_name example.com www.example.com
  location / {
    return 301 https://$host$request_uri;
  }
}

and

server {
  listen 80;
  listen [::]:80;
  server_name example.com www.example.com
  return 301 https://$host$request_uri;
}

What is the difference between these? Is there a reason to use the one or the other?

  • thats a good interesstent question, both should be valid i think – djdomi Oct 10 at 7:57
2

The specification of a location in the first example indicates that you might have locations or paths that should not be redirected to the HTTPS listener, for some reason.

The second example should take all traffic to the given hostname and redirect it.

  • So if I had a location ~ /.well-known/acme-challenge { ... } block as well, then it would be a good idea to use the first example? – lonix Oct 10 at 8:01
  • Yes, that would be one example of an URL path that you might want to exclude from the redirect – HBruijn Oct 10 at 8:02
  • Or, I could use the simpler format, BUT, put the return at the very end. – lonix Oct 10 at 8:03
  • @lonix no, you can’t. Nginx will execute rewrite module directives (return in this case) before it try to look up matching location. – Alexey Ten Oct 10 at 8:23

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.