nginx: Redirecting only non-www to www and exluding other subdomains on ubuntu

Posted May 27, 2015 5.7k views

I have created a new droplet with a fresh installation of nginx on ubuntu 15.04. My current website setup needs naked (non-www) domain to be redirected to www domain, which I can do fairly easily by using the server block as follows using this tutorial:

server {
    listen 80;
    return 301 $scheme://$request_uri;

This code works, but the problem is I want other subdomains to be unaffected. When I use this code, other subdomain for example gets redirected as well. I don’t want this.

I have searched over the internet and tried different configurations, but none of them seems to work.

I only want naked domain to be redirected to and other domains to stay as it is.

i.e. if is requested it should stay the same. I have set all the subdmain as cname to ’@’

I need them to serve some other contents but retain the droplet ip or root www directory.

Can anyone help me with this? :(

P.S. Sorry for bad english.

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

If you set subdomain as CNAME to @ then it will be redirected to

You might want to create a subdomain that have A record to your server. e.g :

then you can create as CNAME to

On nginx. You can create separate configuration for each sub domain on separate file. I usually create the configuration on /etc/nginx/sites-available and make a symlink on /etc/nginx/sites-enabled for configuration / sites that I want to enable

Don’t forget to include /etc/nginx/sites-enabled/* on /etc/nginx/nginx.conf

@DigitFreak I’m facing the exactly same issue (joomla included) did you solved your problem?