Take the 2-minute tour ×
Server Fault is a question and answer site for system and network administrators. It's 100% free, no registration required.

I had a site on domiy.com and now I'm changing the name to namedar.com. I'd like to 301 redirect all requests for domiy.com (or nametyper.com) so that they return namedar.com with the request URI intact.

I've tried simply redirecting everything to namedar.com but that leads to a redirect loop when a request arrives for namedar.com.

rewrite ^ $scheme://nametyper.com$request_uri permanent; # Doesn't work

I'd also like to keep the configuration set up in such a way that all 'www' requests are redirected to the non-www version.

My nginx.conf looks like this at the moment:

server {
  server_name namedar.com www.namedar.com domiy.com www.domiy.com nametyper.com www.nametyper.com;

  # Remove all 'www.' prefixes.
  if ($host ~* www\.(.*)) {
    set $host_without_www $1;
    rewrite ^(.*)$ $scheme://$host_without_www$1 permanent;

How do I write a rewrite directive in order to accomplish this?

share|improve this question

1 Answer 1

up vote 1 down vote accepted

Please let me split your concerns to two steps...

Step 1: www to non-www

server {
  server_name www.domainname.com;
  return 301 $scheme://domainname.com$request_uri;

server {
  server_name domainname.com;
  # [...] regular blocks and directives

Step 2: first_domain.com to second_domain.com

server {
  server_name first_domain.com www.first_domain.com;
  return 301 $scheme://second_domain.com$request_uri;

You may modify the above steps to make it work for any number of domains. Also, you can combine both to happen in a single step.

BTW, in Nginx, if is considered as evil.

share|improve this answer
Is it possible to share configuration settings between server blocks? I have a load of other config settings which I left out of my question for clarities sake. This would all have to be duplicated if I go with your solution. –  duckyfuzz Jun 25 '12 at 15:35
@duckyfuzz From what I know, it is not possible to share configuration settings between server blocks. I wish I'm wrong here. –  Pothi Jun 25 '12 at 15:38
Actually, it tuns out that I don't need to share configuration. I just left all the configuration in the 'namedar.com' server block added another small server block which simply redirects everything to that. Seems to work fine. Thanks. –  duckyfuzz Jun 25 '12 at 15:54
@duckyfuzz Glad to know, it worked for you. –  Pothi Jun 25 '12 at 15:56

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.