0

What I want to do

I want to redirect all to https non-www

http://mytestwebsite.com      > https://mytestwebsite.com
http://www.mytestwebsite.com  > https://mytestwebsite.com
https://www.mytestwebsite.com > https://mytestwebsite.com

I tried this

server {
    listen 80 default_server;
    listen [::]:80 default_server;

    server_name www.mytestwebsite.com mytestwebsite.com;

    return 301 https://mytestwebsite.com$request_uri;
}

server {
    listen 443 ssl http2;
    listen [::]:443 ssl http2;

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

    server_name www.mytestwebsite.com mytestwebsite.com;
    ssl_certificate /home/mysite/ssl.cert;
    ssl_certificate_key /home/mysite/ssl.key;
    # SSL configuration
    # Other configurations
}

server {
         server_name "~^www\.(.*)$" ;
         return 301 $scheme://$1$request_uri ;
}

With this, all works fine, except

https://www.mytestwebsite.com > https://mytestwebsite.com

I always get https://www.mytestwebsite.com......

I tried many solutions from stackoverflow, google etc.. and nothing works. https always have www...

How to remove www from https links?

Aleksandar
  • 59
  • 1
  • 7
  • Does this answer your question? [Nginx no-www to www and www to no-www](https://stackoverflow.com/questions/7947030/nginx-no-www-to-www-and-www-to-no-www) – Rob Apr 14 '21 at 23:00
  • Thanks, already tried but unfortunately doesn't work.. – Aleksandar Apr 14 '21 at 23:07
  • Your configuration looks fine. The last `server` block does nothing, but the `if` block should work unless there is a typo or you forgot to restart the server. Did you forget to reset the browser's cache when you tested it? It's safer to test redirection using `curl`. – Richard Smith Apr 15 '21 at 08:37

1 Answers1

2

Firstly check if your dns record is configured for mytestwebsite.com. If it is not, the add A record via domain provider dashboard.

Then you can have something of this sort:

server {
  #listen and all other stuff

  server_name www.mytestwebsite.com;

  location / {
    return 301 https://mytestwebsite.com/$uri;
  }
}

What it will do is if any request is sent to www.mytestwebsite.com, it will be 301 Moved Permanently to mytestwebsite.com.

NetanMangal
  • 309
  • 1
  • 9