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

I want to redirect from www.mydomain.com to domain.com in nginx. I search the internet and found two ways:

First way

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

Second way

server {
            listen   80;
            server_name  www.domain.com;
            return 301 $scheme://domain.com$request_uri;
}

Both ways work. But Which one should i use and why?

share|improve this question
add comment

1 Answer 1

up vote 5 down vote accepted

Second way is better...

server {
  listen   80;
  server_name  www.domain.com;
  return 301 $scheme://domain.com$request_uri;
}

Why

Let me quote directly from the official Nginx wiki at http://wiki.nginx.org/Pitfalls#Taxing_Rewrites ...

By using the built-in variable $request_uri,
we can effectively avoid doing any capturing or matching at all,
and by using the return directive,
we can completely avoid evaluation of regular expression.

My own thoughts...

By default, the regex is costly and will slow down the performance.

share|improve this answer
add comment

Your Answer

 
discard

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.