Redirecting all subdomains to www in nginx with virtual hosting

June 17th, 2011
nginx, tech
If you look for how to redirect to 'www.example.com', you see people writing something where you have to know the hostname, or you have to know all subdomains. What if we need to be much more general, because this server hosts multiple domains, someone might come in on arbitrary subdomain, and we want all requests to go to 'www.REQUESTED_DOMAIN.com'? I came up with the following (it goes in the 'server' block'):
        server_name   ~^(?<subdomains>.+\.)?(?<domain>[^.]+\.[^.]+)$;

        if ($subdomains != www.) {
          rewrite  ^/(.*)$  http://www.$domain/$1  permanent;
        }
  
This will do:
  • www.example.com: no change
  • example.com: www.example.com
  • mail.example.com -> www.example.com
  • mail.example2.com -> www.example2.com
  • foo.bar.baz.example.com -> www.examplecom
Note that it assumes only one level of tld. So if your site is '.co.uk' or something, it will redirect all requests to 'www.co.uk', which is unlikely to be what you want.

Recent posts on blogs I like:

Jealousy In Polyamory Isn't A Big Problem And I'm Tired Of Being Gaslit By Big Self-Help

The nuance is in the post, guys

via Thing of Things July 18, 2024

Trust as a bottleneck to growing teams quickly

non-trust is reasonable • trust lets collaboration scale • symptoms of trust deficit • how to proactively build trust

via benkuhn.net July 13, 2024

Coaching kids as they learn to climb

Helping kids learn to climb things that are at the edge of their ability The post Coaching kids as they learn to climb appeared first on Otherwise.

via Otherwise July 10, 2024

more     (via openring)