Nginx redirect only root domain but not subdomain to www

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

server { listen 80; server_name; return 301$request_uri; }

server { listen 80; server_name; location / { proxy_pass; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection ‘upgrade’; proxy_set_header Host $host; proxy_cache_bypass $http_upgrade; } }

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.

Submit an answer

This textbox defaults to using Markdown to format your answer.

You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!

Sign In or Sign Up to Answer

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.

Want to learn more? Join the DigitalOcean Community!

Join our DigitalOcean community of over a million developers for free! Get help and share knowledge in Q&A, subscribe to topics of interest, and get courses and tools that will help you grow as a developer and scale your project or business.


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.

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.