使用 NGINX 將站點代理到另一個站點

使用 NGINX 將站點代理到另一個站點

我有一個網站,其中包含一些網址(http://位置:連接埠/)並想使用 NGINX 來代理它。

我有另一個網站,位於 (http://位置2:連接埠2)並且也想代理它。

  1. http://main.com站點 1 透過和訪問
  2. http://main.com/site2網站 2 透過其所有子連結訪問

我的嘗試失敗了。

server {
    listen  80;

    index index.html;

    location / {
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header Host $http_host;
        proxy_set_header X-NginX-Proxy true;

        proxy_pass http://landing-page:5000;
        proxy_redirect off;
    }

    location /insights {
        return 302 $uri/;
    }

    location /insights/ {
        # proxy_set_header X-Real-IP $remote_addr;
        # proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        # proxy_set_header Host $http_host;
        # proxy_set_header X-NginX-Proxy true;

        rewrite ^/insights/?(.*) /$1 break;

        proxy_pass http://ghost:2368/;
        # proxy_redirect off;
    }
}

附加資訊

我在 Docker 上運行 NGINX,並且必須將 Mac 上的連接埠 80 對應到 8080。

我發現是這樣的:

  1. http://localhost:8080/insightshttp://localhost/insights/將瀏覽器中的URL 設定為
  2. http://localhost:8080/insights/ghost將 URL 設定為http://localhost:8080/ghost/
  3. http://localhost:8080/insights/將 URL 設定為http://localhost:8080/insights/
  4. http://localhost:8080/insights/ghost/將 URL 設定為http://localhost:8080/insights/ghost/

任何以斜線結尾的網址似乎都可以正常運作。為什麼?

答案1

您的location /區塊應該位於文件的末尾。位置區塊按順序處理,第一個符合的區塊將被執行。由於location /匹配每個請求,因此它總是會被執行。

一般來說,您應該先擁有最具體的區塊,然後是不太具體的區塊,最後location /以所有其他請求結束。

你的文件應該這樣佈局:

server {
    listen  80;

    index index.html;

    location /insights/ {
        # proxy_set_header X-Real-IP $remote_addr;
        # proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        # proxy_set_header Host $http_host;
        # proxy_set_header X-NginX-Proxy true;

        rewrite ^/insights/?(.*) /$1 break;

        proxy_pass http://ghost:2368/;
        # proxy_redirect off;
    }

    location /insights {
        return 302 $uri/;
    }

    location / {
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header Host $http_host;
        proxy_set_header X-NginX-Proxy true;

        proxy_pass http://landing-page:5000;
        proxy_redirect off;
    }
}

相關內容