Tom Heston
Tom Heston

Reputation: 135

Redirect Nginx HTTP/HTTPS www to non www

I have just purchased a Wildcard SSL certificate that allows me to have access to dynamic sub-domains. I can access the following domains fine with my config:

https://test.example.co/

https://example.co/

http://example.co/ goes to -> https://example.co/

So I'm forcing all HTTP to HTTPS and removing the www.

My problem is that I have dynamic sub-domains which allow users to have any sub-domain they want (https://user1.example.co, https://user2.example.co, https://user3.example.co).

My problem is when a user visits http://www.user1.example.co/ or https://www.user1.example.co/ I get the following:

NET::ERR_CERT_COMMON_NAME_INVALID

My config:

server {
    server_name www.example.co;
    return 301 $scheme://example.co$request_uri;
}
server {
    listen 443;
    ssl on;
    ssl_certificate /etc/nginx/blah;
    ssl_certificate_key /etc/nginx/blah;

    server_name example.co *.example.co;

    ssl_protocols TLSv1 TLSv1.1 TLSv1.2;

    location / {
        proxy_pass http://127.0.0.1:3000;
        proxy_set_header X_FORWARDED_PROTO https;
        proxy_set_header  X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header  Host $http_host;
        proxy_set_header  X-Url-Scheme $scheme;
        proxy_redirect    off;
        proxy_max_temp_file_size 0;
    }
}

I've removed the certificate and the logic inside but my goal is to have any www. removed. So it would like so:

http://www.user1.example.com -> https://user1.example.com http://www.user2.example.com -> https://user2.example.com

And of course all my domains above work like they are now.

Upvotes: 2

Views: 539

Answers (1)

Tarun Lalwani
Tarun Lalwani

Reputation: 146490

It is only possible if you have all the subdomain names available before hand.

You can have multiple subdomains with wildcard inside the same certificate. So you will need a certificate with all subdomains that you are going to use

*.example.com
*.user1.example.com
*.user2.example.com
*.user3.example.com
*.user4.example.com

Which means you can't dynamic add new subdomains to the list, as it would require regeneration of the certificate.

A wildcard inside a name only reflects a single label and the wildcard can only be leftmost. Thus no ..example.org, www.*.example.org are possible. And *.example.org will neither match example.org nor www.subdomain.example.org, only subdomain.example.org.

But you can have multiple wildcard names inside the same certificate, that is you can have *.example.org and *.subdomain.example.org inside the same certificate

SSL Multilevel Subdomain Wildcard

Upvotes: 2

Related Questions