0

I have an Nginx web server and I need to:

  1. Redirect all HTTP (both www and non-www) to HTTPS
  2. Redirect all HTTPS non-www to www

I know that I can use different server{} blocks but I want to achieve this with one server block using "if" statements, so here is my actual Nginx vhost configuration:

server {
        listen 80;
        listen 443 ssl http2;
        server_name website.com www.website.com;

        if ($scheme = "http") {
            return 301 https://www.website.com$request_uri;
        }

        if ($host = "website.com") {
            return 301 https://www.website.com$request_uri;
        }

        [...]
}

It works fine without problems:

http://website.com     => https://www.website.com
http://www.website.com => https://www.website.com
https://website.com    => https://www.website.com

My questions is if my configuration is correct.

Thanks!

user2972081
  • 101
  • 1
  • 2
    Possible duplicate of [In Nginx, how can I rewrite all http requests to https while maintaining sub-domain?](http://serverfault.com/questions/67316/in-nginx-how-can-i-rewrite-all-http-requests-to-https-while-maintaining-sub-dom) . Read this, your configuration above is quite incorrect. Also Google "Nginx if is evil" – Tim Feb 02 '17 at 18:45
  • Why do you want toimplement this with `if`? – Tero Kilkanen Feb 02 '17 at 20:46

0 Answers0