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?

1 Answer 1

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.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .