Question

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

Posted May 27, 2015 5k views
NginxJoomla

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.

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.

×
2 answers

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

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

Submit an Answer