0

I'm having trouble figuring out my nginx config.

My config is supposed to force the use of https and no www. Some subdomains api.domain.com, api.staging.domain.com is allowed. The last mentioned is currently configured in another conf file, not enclosed here.

Currently my problem is that this seems to allow www. I need www to be 301 redirected to no www. The subdomain www is setup as a cname in the dns config.

Can someone help me out?

server {
        listen          54.00.00.00;
        server_name     54.00.00.00;
        rewrite         .* https://domain.com$request_uri permanent;
}
server {
        listen          80;
        return          301 https://$host$request_uri;
}
server {
        listen          443 default ssl;
        server_name     domain.com api.domain.com;
        root            /var/www/domain.com/current/web;

        ##
        # Certificate Settings
        ##

        ssl_certificate         /etc/nginx/ssl/domain.com.pem;
        ssl_certificate_key     /etc/nginx/ssl/domain.com.key;
charliexx
  • 423
  • 2
  • 7
  • 15

1 Answers1

0

You problem is that this server

server {
    listen          80;
    return          301 https://$host$request_uri;
}

Matches all servers, even the ones with www mind that if you are requesting http://www.example.com, $host will be www.example.com, so you end up redirecting to the https version with www.

If you want to do a catch all and still strip www from those who have it I suggest it would be better to use regex in the server name

server {
    server_name ~^(www\.)?(?<domain>.+)$;
    return 301 https://$domain$request_uri;
}
Mohammad AbuShady
  • 40,884
  • 11
  • 78
  • 89