NGINX を使ってサイトを別のサイトにプロキシする

NGINX を使ってサイトを別のサイトにプロキシする

私は(にいくつかのURLを持つサイトを持っていますhttp://場所:ポート/) であり、NGINX を使用してプロキシしたいと考えています。

私には別のサイトがあります。http://場所2:ポート2) をプロキシして、そのようにしたいと考えています。

  1. サイト1はhttp://main.com
  2. サイト2は、http://main.com/site2そのすべてのサブリンクを介してアクセスされます。

私の試みは失敗している。

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/ghostURLを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/

末尾にスラッシュが付いた任意の URL が適切に機能するようです。なぜでしょうか?

答え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;
    }
}

関連情報