Introduction

Yesterday I’ve written a post about how to redirect traffic from www.domain.com to domain.com using Nginx.

It is using an if statement inside the server section in the nginx.conf file, there is another way to do it.

It is to create two server section, and redirect the traffic from one of them to the other:

Strip www from url with nginx redirect

server {
    server_name  www.domain.com;
    rewrite ^(.*) http://domain.com$1 permanent;
}

server {
    server_name  domain.com;
    #The rest of your configuration goes here#
}

What you need to do, it use the same IP in your DNS server for both

domain.com and www.domain.com, and when the browser asks for www.domain.com will be redirected to domain.com and will ask to the same server that info, in that case, it will get the proper answer from your server.

Add the www to the url with nginx redirect

If what you need is the opposite, to redirect from domain.com to www.domain.com, you can use this:

server {
    server_name  domain.com;
    rewrite ^(.*) http://www.domain.com$1 permanent;
}

server {
    server_name  www.domain.com;
    #The rest of your configuration goes here#
}

As you can imagine, this is just the opposite and works the same way the first example.

What I like about this, is that you can actually use this method to forward other domains you may own to an specific domain, let’s see.

Imagine you own:

  • domain.com
  • domain.net
  • domain.org

Your site is located at www.domain.com, you may write a configuration file like this:

server {
    server_name domain.org;
    rewrite ^(.*) http://www.domain.com$1 permanent;
}
server {
    server_name www.domain.org;
    rewrite ^(.*) http://www.domain.com$1 permanent;
}

server {
    server_name domain.net;
    rewrite ^(.*) http://www.domain.com$1 permanent;
}
server {
    server_name www.domain.net;
    rewrite ^(.*) http://www.domain.com$1 permanent;
}

server {
    server_name domain.com;
    rewrite ^(.*) http://www.domain.com$1 permanent;
}
server {
    server_name www.domain.com;
    #From here you start your Nginx server normal configuration#
}

Do not forget to manage your DNS server and on each zone assign the same IP for all

  • domain.com
  • www.domain.com
  • domain.org
  • www.domain.org
  • domain.net
  • www.domain.net