Nginx에서 기본 리디렉션 설정

Nginx에서 기본 리디렉션 설정

기존 경로가 정의되지 않은 경우 클라이언트를 리디렉션하는 방법이 필요합니다. return 301 구성을 넣으면 nginx는 모든 위치 구성을 무시하는 것 같습니다. 모든 것을 리디렉션합니다.

리디렉션의 호스트 이름은 동적이어야 합니다(클라이언트에서 가져옴). 이러한 서버는 실제로 컨테이너이며 개발/생산 환경에 배포됩니다. 따라서 클라이언트 URL은 dev.example.com과 같은 것에서 example.com으로 변경됩니다. 환경에 따라 구성 교환을 수행하지 않는 것이 좋습니다.

RHEL에서 v1.18을 사용하고 있습니다. 프록시된 서버는 해당 개발자가 관리하는 Angular 앱입니다.

server {
  listen 80;
  server_name _;

  index index.html;

  location = /service/a {
    proxy_pass http://svc-a.local/service/a/;
  }
  location /service/a/ {
    proxy_pass http://svc-a.local/service/a/;
  }

  location = /service/b {
    proxy_pass http://svc-b.local/service/b/;
  }
  location /service/b/ {
    proxy_pass http://svc-b.local/service/b/;
  }

  location = /service/x {
    proxy_pass http://svc-x.local/service/x/;
  }
  location /service/x/ {
    proxy_pass http://svc-x.local/service/x/;
  }

  location = /home {
    proxy_pass http://home.local/home/;
  }
  location /home/ {
    proxy_pass http://home.local/home/;
  }

  # kubernetes probes this, but fails getting 301
  location /nginx_status {
    stub_status on;
    acccess_log off;
  }

  # IF NO MATCH FROM ABOVE THEN GO TO /HOME

  # try #1
  return 301 http://$host/home/;

  # try #2
  location = / {
    return 301 http://$host/home/;
  }

  # try #3
  return 301 /home/;

  # try #4
  location = / {
    proxy_pass http://home.local/home/;
  }
}

답변1

return 301위치 블록 외부에 있는 규칙은 전체 서버 블록에 적용되며 위치 블록보다 우선합니다 . 대신 시도 #2에서와 같이 기본/대체 위치 블록을 정의할 수 있지만 등호( =)는 사용하지 않습니다. 등호는 정확한 일치를 지정하며 대신 모든 요청과 일치하도록 접두사 일치를 원합니다.

예를 들어:

server {
  listen 80;
  server_name _;

  index index.html;

  location = /service/a {
    proxy_pass http://svc-a.local/service/a/;
  }
  location /service/a/ {
    proxy_pass http://svc-a.local/service/a/;
  }

  location /service/b/ {
    proxy_pass http://svc-b.local/service/b/;
  }

  location = /service/x {
    proxy_pass http://svc-x.local/service/x/;
  }
  location /service/x/ {
    proxy_pass http://svc-x.local/service/x/;
  }

  location = /home {
    proxy_pass http://home.local/home/;
  }
  location /home/ {
    proxy_pass http://home.local/home/;
  }

  # kubernetes probes this, but fails getting 301
  location /nginx_status {
    stub_status on;
    acccess_log off;
  }

  # IF NO MATCH FROM ABOVE THEN GO TO /HOME

  location / {
     return 301 http://$host/home/;
  }
}

관련 정보