在 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規則位於任何位置區塊之外時,該規則將套用於整個伺服器區塊並優先於位置區塊。您可以定義一個預設/後備位置區塊,如您的 try #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/;
  }
}

相關內容