4

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?

Christos Baziotis
  • 303
  • 1
  • 4
  • 14

1 Answers1

6

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 Pitfalls and Common Mistakes:

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.

techraf
  • 4,163
  • 8
  • 27
  • 44
Pothi Kalimuthu
  • 5,734
  • 2
  • 24
  • 37