Question

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

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;
    server_name example.com;
    return 301 $scheme://www.example.com$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 cdn.domain.com 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 www.domain.com and other domains to stay as it is.

i.e. if cdn.domain.com 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.


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.

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

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

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

sites.domain.com

then you can create anothersubdomain.domain.com as CNAME to sites.domain.com

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