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

May 27, 2015 1.7k views
Joomla Nginx

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.

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

  • Hello @sumodirjo

    Thank you for ur input. I have subdomain setup as an alias of my

    everything worked on Apache configuration. I have moved my website to Do from shared host. I am new to nginx so this can be little tricky for me. Don't get me wrong I have managed VPs before and working on Linux is not new to me. It's just I am not too familiar with nginx and how it works.

    My is used to serve the website and 3 other subdomains say,, to serve the contents such as images, CSS or other resources. Which are all relative to root / same as and not subdirectories.

    Can you elaborate a little more with example or point me to the right direction?

  • by Etel Sverdlov
    This tutorial shows you how to set up a new directory, how to grant the correct permissions, how to add content to a new page, how to turn on virtual hosting, and how to, if needed, set up local hosts. Virtual Hosts are used to run more than one website or domain off of a single server and IP address. When used with nginx, virtual hosts are called Server Blocks. This tutorial covers setting up server blocks on an Ubuntu server.

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

Have another answer? Share your knowledge.