Nginx에서 다른 도메인으로 리디렉션하는 방법과 경로 및 하위 도메인도 유지하는 방법은 무엇입니까?

Nginx에서 다른 도메인으로 리디렉션하는 방법과 경로 및 하위 도메인도 유지하는 방법은 무엇입니까?

예를 들어, 저는 도메인이 olddomain.com있고newdomain.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/

관련 정보