3

I have a domain set up with wildcard subdomains for white label access. I'm trying to safeguard against people typing in http://www.subdomain.domain.com/ but struggling to find a solution. (I already have a rewrite in action to always use a secure protocol.)

My current setup is this (well, the relevant part):

server {
    listen 80;
    server_name  domain.com *.domain.com;
    rewrite ^ https://$http_host$request_uri? permanent;
}

server {
    listen 443;
    ssl on;
    ssl_certificate /path/to/certificate.crt;
    ssl_certificate_key /path/to/certificate.key;
    server_name domain.com *.domain.com;

    ...
}

What I have achieved is that http://domain.com and http://sub.domain.com both redirect to the https protocol, in other words https://domain.com and https://sub.domain.com respectively. What I'd still like to achieve on top is that both http://www.domain.com and https://www.domain.com redirect to https://domain.com and that both http://www.sub.domain.com and https://www.sub.domain.com redirect to https://sub.domain.com as well.

Could anyone help, please?

(PS: I was even thinking of applying a global nginx setup to remove the www part of the URL for ALL domains running on the same server at once if that's an option.)

Barnabas Kecskes
  • 1,861
  • 17
  • 24

1 Answers1

2

To drop the leading www. sequence from the requested server name, place this if block near the top of your SSL server container (before any other URI processing directives):

if ($http_host ~* ^www\.(.*)$ ) 
{ 
    return 301 $scheme://$1$request_uri;
}

Generally if should be used very carefully, but it is perfectly fine in this case.

Richard Smith
  • 45,711
  • 6
  • 82
  • 81
  • We use this for dynamic subdomains for multi tenants where www will cause issues and this method works great and is barely noticeable in the redirect. This reduces the need for any sort of checks in the application layer and handles it more directly at the proxy. – Garrick Crouch Oct 13 '21 at 15:28