rewrite two www domains to same non-www domain on nginx

August 8, 2014 5k views

I have added two domains to my droplet ( and

I want to rewrite both www and non-www to i.e.: => => => =>

It feels like I have tried every combination of server blocks in nginx but I cannot get it to work properly.

nginx version: nginx/1.4.6 (Ubuntu)

How do I set this up?

1 comment
  • # host_without_www
    if ( $host ~* ^www\.(?<nowww>.*)$ ) {
        rewrite .* $scheme://$nowww$request_uri permanent;
    # host_with_www
    if ( $host ~* ^(?!www\.) ) {
        rewrite .* $scheme://www.$host$request_uri permanent;
3 Answers

Make sure that the "www" records exist for each domain: www CNAME @

Then, edit the current virtualhosts for your domain name and make sure server_name is set to and not

Finally, add the following virtualhost for each domain:

server {
    listen 80;

    return 301 $scheme://$request_uri;

Don't forget to restart nginx after adding the virtualhosts.

Hi there,

I've tried the above and it just doesn't seem to work for me. Can you explain to me what you mean by "Make sure that the "www" records exist for each domain: www CNAME @"?


I have currently a non-www domain, but would like to redirect the www to mine so I believe i have to add an entry to the CNAME field but not quite sure what values to insert. Anyone that could give me a helping hand?

Have another answer? Share your knowledge.