nginxでリバースプロキシを設定した際にリダイレクト先の相対パスが機能しなくなってしまう
ググろうにも状況をうまく言語化することができなかったため、こちらに質問を投稿させていただきました。個人開発をしており、業界で活躍されている方からすると伝わらない部分もあるかと思いますが、ご容赦ください。
現在、DockerComposeを用いてwebアプリケーション用のサーバーを立てようとしております。
まずは勉強用として、viteとreact、そしてリバースプロキシ用のnginxで構成されるプロジェクトを作成しました。nginxとreactそれぞれをdocker composeコマンドにて起動させることには成功したのですが、いざnginxを用いてreactにリダイレクトすると、html内に記述されている相対パスの参照先が
http://<サーバーのIP>:5173/src/main.tsx
http://<サーバーのIP>/src/main.tsx
となってしまい、404エラーが発生してしまいます。こちらについて、404エラーを発生させないようにするには、どうすればよいでしょうか?ゆくゆくはhttp://<サーバーのIP>:5173へのアクセスを制限し、すべてnginxを介するようにしたいと思っています。
ソースコード
※すでに動いているwebサーバーがあり、ネットワークカードを追加して動かしているので、localhostが使えません。
/
├─ docker
│ ├─ nginx
│ │ └─ nginx.conf
│ └─ nodejs
│ └─ Dockerfile
├─ react
│ ├─ .gitignore
│ ├─ eslint.config.js
│ ├─ index.html
│ ├─ package-lock.json
│ ├─ package.json
│ ├─ README.md
│ ├─ tsconfig.app.json
│ ├─ tsconfig.json
│ ├─ tsconfig.node.json
│ ├─ vite.config.ts
│ ├─ node_modules
│ │ └─ ...
│ ├─ public
│ │ └─ vite.svg
│ └─ src
│ ├─ App.css
│ ├─ App.tsx
│ ├─ index.css
│ ├─ main.tsx
│ ├─ vite-env.d.ts
│ └─ assets
│ └─ react.svg
└─ docker-compose.yml
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<link rel="icon" type="image/svg+xml" href="/vite.svg" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Vite + React + TS</title>
</head>
<body>
<div id="root"></div>
<script type="module" src="/src/main.tsx"></script>
</body>
</html>
<html lang="en"><head>
<script type="module">import { injectIntoGlobalHook } from "/@react-refresh";
injectIntoGlobalHook(window);
window.$RefreshReg$ = () => {};
window.$RefreshSig$ = () => (type) => type;</script>
<script type="module" src="/@vite/client"></script>
<meta charset="UTF-8">
<link rel="icon" type="image/svg+xml" href="/vite.svg">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Vite + React + TS</title>
</head>
<body>
<div id="root"></div>
<script type="module" src="/src/main.tsx"></script>
</body></html>
Failed to load resource: the server responded with a status of 404 (Not Found) client:1
Failed to load resource: the server responded with a status of 404 (Not Found) main.tsx:1
Failed to load resource: the server responded with a status of 404 (Not Found) @react-refresh:1
Failed to load resource: the server responded with a status of 404 (Not Found) vite.svg:1
http {
server {
listen 0.0.0.0:80;
server_name <サーバーのIP>;
location /react/ {
proxy_pass http://host.docker.internal:5173/;
proxy_redirect off;
}
}
}
services:
react:
container_name: 'React'
build:
context: .
dockerfile: ./docker/nodejs/Dockerfile
ports:
- 5173:5173
volumes:
- ./react/:/var/www/html/node
environment:
- WATCHPACK_POLLING=true
tty: true
proxy:
image: nginx:1.29.0
container_name: 'Proxy'
volumes:
- ./docker/nginx/nginx.conf:/etc/nginx/nginx.conf
- ./src:/var/www/html
ports:
- 80:80
extra_hosts:
- "host.docker.internal:host-gateway"