Nginx で、別のドメインにリダイレクトしながら、パスとサブドメインも保持するにはどうすればよいですか?

Nginx で、別のドメインにリダイレクトしながら、パスとサブドメインも保持するにはどうすればよいですか?

例えば、私はドメインを持っていolddomain.comnewdomain.com

リクエストのリダイレクトを動作させる方法は次のとおりです。

sub.olddomain.com/hello/world -> sub.newdomain.com/hello/world olddomain.com/hello/world -> newdomain.com/hello/world

サブドメインは多数あるため、理想的にはサブドメインごとにルールを作成したくありません。

これは解決策のように思えます:

server {
  listen 80;
  server_name olddomain.com *.olddomain.com;
  rewrite ^(/)(.*)$ http://newdomain.com/$2 permanent;
}

newdomain.com/pathただし、サブドメインでは機能しません。サブドメインに関係なく、すべてのサブドメインがリダイレクトされるためです。

答え1

次のようなものを探しているようです:

if ($http_host ~ (.*)\.olddomain\.com) {
    set $subdomain $1;
    rewrite (.*)$ http://$subdomain.newdomain.com$1 permanent;
}
rewrite ^(/)(.*)$ http://newdomain.com/$2 permanent;

これらは私のテストケースです

$ curl -I -H "Host: test1.olddomain.com" nginx1.tst
HTTP/1.1 301 Moved Permanently
Server: nginx/1.4.4
Date: Thu, 08 May 2014 19:40:33 GMT
Content-Type: text/html
Content-Length: 184
Connection: keep-alive
Location: http://test1.newdomain.com/

$ curl -I -H "Host: test1.test2.olddomain.com" nginx1.tst
HTTP/1.1 301 Moved Permanently
Server: nginx/1.4.4
Date: Thu, 08 May 2014 19:40:38 GMT
Content-Type: text/html
Content-Length: 184
Connection: keep-alive
Location: http://test1.test2.newdomain.com/

$ curl -I -H "Host: test1.test2.olddomain.com" nginx1.tst/with-something/appended.html
HTTP/1.1 301 Moved Permanently
Server: nginx/1.4.4
Date: Thu, 08 May 2014 19:40:54 GMT
Content-Type: text/html
Content-Length: 184
Connection: keep-alive
Location: http://test1.test2.newdomain.com/with-something/appended.html

$ curl -I -H "Host: olddomain.com" nginx1.tst
HTTP/1.1 301 Moved Permanently
Server: nginx/1.4.4
Date: Thu, 08 May 2014 19:41:10 GMT
Content-Type: text/html
Content-Length: 184
Connection: keep-alive
Location: http://newdomain.com/

関連情報