Nginx redirect only root domain but not subdomain to www

June 28, 2017 1.2k views
Nginx DNS Ubuntu 16.04

Currently I'm using setting below to redirect non-www domain to www domain and it's working fine:

server {
listen 80;
servername example.com;
return 301 http://www.example.com$request
uri;
}

server {
listen 80;
servername www.example.com;
location / {
proxy
pass http://www.example.com:8888;
proxyhttpversion 1.1;
proxysetheader Upgrade $httpupgrade;
proxy
setheader Connection 'upgrade';
proxy
setheader Host $host;
proxy
cachebypass $httpupgrade;
}
}

However, now I would like to allow wildcard subdomain but it seems like all the subdomains were being redirect to www.domain.com. So my question is how can I make it only redirect the root domain to www only and excluding all other subdomain? Thanks.

2 Answers

Hi @menuassist

With that configuration, Nginx should not redirect wildcard subdomains. Are you sure you don't have another configuration file some place messing with the redirect?
Can you show the wildcard subdomain configuration example?

Also, please use the </> button in the comment editor to save the code formatting.

@menuassist

Normally, to setup Wild Cards, you'd need to have a * A entry in your DNS (pointing to your Droplet IP) and then a Wild Card entry in server_name.

i.e.

A       *       DROPLET_IP
server_name example.com *.example.com;

The above server_name would direct any sub-domain that doesn't have an existing server block to the block you set it up in.

Your current block shouldn't technically allow sub-domains to resolve to that server block, unless you do have another server block setup that's conflicting with the one you've posted.

Have another answer? Share your knowledge.