Nginx proxy for react application(nodejs)

使用 nginx 代理 react app
假設 domain 為 local.react

當然可以用 npm, nodejs 直接做為 server

但是多一層 nginx 彈性更多、更自由
也方便讓同一台機器上同時有多個專案


如果使用 cra(create react app),透過 npm run start 啟用 server
(開發時使用)

e.g. local.react.conf

server {
    server_name local.react;

    listen 80;
    listen 443 ssl http2;

    # access_log /var/www/express-test/storage/logs/access.log main;
    # error_log /var/www/express-test/storage/logs/error.log;

    location / {
        proxy_pass http://WORKSPACE:3000;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection 'upgrade';
        proxy_set_header Host $host;
        proxy_cache_bypass $http_upgrade;
    }
}
  • access_log, error_log 依需求設定
  • proxy_pass 設定為 npm run start 所提供的 url,e.g.

若為純 js react app(npm run build)

e.g. local.react.conf

server {
   server_name local.react;
   root /var/www/react-to-do/build;

    listen 80;
    listen 443 ssl http2;

    #access_log /var/www/react-to-do/access-local.react.log;
    #error_log /var/www/react-to-do/error-local.react.log;

   index index.html index.htm;
   location / {
      try_files $uri /index.html =404;
   }
}
  • 設定 root 指定 bundle 完的檔案位置
1個讚