Ubuntu - 26.04 - Server - nginx ポート振り分け


 


1. 概要
2. 状況
3. 設定
4. 参考サイト

1. 概要

 これは、「Ubuntu」というよりは、「nginx」の話なのですが、現在(2026年10月26日)、他に書くところもないので、ここに記述します。

2. 状況

 現在、「flask」でコンテンツを表示しているのですが。

https://example.com/
 で、「flask1.py」へ転送しています。  これに加えて。

https://example.com/222/
https://example.com/333/
 にアクセスする際は、それぞれ、「flask2.py」「flask3.py」へ転送するにはどうするか。  ちゅう話です。

3. 設定


/etc/nginx/sites-available/default
 を変更することになるのですが、同じ記述が3回並ぶことになるので、インクルードするファイルを作成します。

sudo vi /etc/nginx/snippets/flask-proxy.conf
 下記を記述します。

proxy_redirect off;

proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;

add_header Access-Control-Allow-Origin "*" always;
add_header Access-Control-Allow-Methods "GET, POST, OPTIONS" always;
add_header Access-Control-Allow-Headers "Content-Type" always;

if ($request_method = 'OPTIONS') {
    return 204;
}

sudo vi /etc/nginx/sites-available/default
 80番ポートの設定に。

server {

	・・・	略	・・・

	location / {

	・・・	略	・・・

	}
}
 という記述があるならば、「location / {」~「}」をこう書きます。

	absolute_redirect off;

	location / {
	    proxy_pass http://127.0.0.1:5000/;
	    include snippets/flask-proxy.conf;
	    proxy_set_header X-Forwarded-Proto $http_x_forwarded_proto;
	}

	location /web/ {
	    proxy_pass http://127.0.0.1:5001/;
	    include snippets/flask-proxy.conf;
	    proxy_set_header X-Forwarded-Proto $http_x_forwarded_proto;
	    proxy_set_header X-Forwarded-Prefix /222;
	}

	location /dashboard/ {
	    proxy_pass http://127.0.0.1:5002/;
	    include snippets/flask-proxy.conf;
	    proxy_set_header X-Forwarded-Proto $http_x_forwarded_proto;
	    proxy_set_header X-Forwarded-Prefix /333;
	}
 443番ポートの設定に。

server {

	・・・	略	・・・

	location / {

	・・・	略	・・・

	}
}
 という記述があるならば(「http」は「https」へ転送)、「location / {」~「}」をこう書きます。

    absolute_redirect off;

    location / {
        proxy_pass http://127.0.0.1:5000/;
        include snippets/flask-proxy.conf;
        proxy_set_header X-Forwarded-Proto "https";
    }

    location /web/ {
        proxy_pass http://127.0.0.1:5001/;
        include snippets/flask-proxy.conf;
        proxy_set_header X-Forwarded-Proto "https";
        proxy_set_header X-Forwarded-Prefix /222;
    }

    location /dashboard/ {
        proxy_pass http://127.0.0.1:5002/;
        include snippets/flask-proxy.conf;
        proxy_set_header X-Forwarded-Proto "https";
        proxy_set_header X-Forwarded-Prefix /333;
    }
 もしかしたら、「flask」の方も設定を変える必要があるかもしれませんが、「nginx」の方は、これで「OK」なはずで。

sudo nginx -t
 で文法チェックして、再起動します。

sudo systemctl reload nginx
 「flask」側も対応できていれば、下記で確認します。

curl -I https://example.com/222/

curl -I https://example.com/333/

4. 参考サイト

 本ページは、「Claude」上等兵を参考にさせていただきました。

audiobook.jp
5G CONNECT
【usus ウズウズ】
アフィリエイトのアクセストレード
U-NEXT
それがだいじWi-Fi
葬送のフリーレン Prime Video
薬屋の独り言
損保との違い
ベルリッツ
Amazonギフトカード
JETBOY
健康サポート特集
ネットオークションの相場、統計、価格比較といえばオークファン
TikTok Shop 【リピート用プログラム】
サウンドハウス
ハイスピードプラン
EaseUS
earthcar(アースカー)