Nginx redirect only root domain but not subdomain to www

Posted June 28, 2017 9.9k views
NginxDNSUbuntu 16.04

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

server {
listen 80;
return 301$request

server {
listen 80;
location / {
proxyhttpversion 1.1;
proxysetheader Upgrade $httpupgrade;
setheader Connection ‘upgrade’;
setheader Host $host;
cachebypass $httpupgrade;

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

These answers are provided by our Community. If you find them useful, show some love by clicking the heart. If you run into issues leave a comment, or add your own answer to help others.

Submit an Answer
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.


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.


A       *       DROPLET_IP
server_name *;

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.

  • nice info for WildCards subdomain @jtittle i m looking for wildcard subdomains

    first set A * to IP (where what and how to set A * in nginx?)
    then write a server block server_name *;

    i want to redirect all my subdomains to my index.php file
    * to