react項目(windows本地)打包部署到服務器(阿里云ubuntu)

前提:使用react-router的BrowserRouter路由模式(單頁開發,url切換時需要服務器始終返回index.html)

一、根目錄部署

1、修改package.json文件

添加"homepage" :"http://xxx.com/" #解決部署到服務器后刷新頁面出錯的問題

image.png

2、項目根目錄執行npm run bulid

image.png

3、將打包后在根目錄生成的build文件夾上傳到服務器

image.png

4、ubuntu安裝nginx

  • apt-get update #更新源
  • apt-get install nginx #安裝nginx
  • vim /etc/nginx/nginx.conf #修改配置文件
server {
  listen 80; #端口
  server_name xx.xx.xxx.xxx; #ip或域名 
  root /opt/React/build/; #文件夾目錄
  index index.html index.htm;
  location / {
      try_files $uri $uri/ /index.html;
  }
  location ^~ /assets/ {
      gzip_static on;
      expires max;
      add_header Cache-Control public;
  }
  error_page 500 502 503 504 /500.html;
  client_max_body_size 20M;
  keepalive_timeout 10;
}
image.png
  • service nginx restart #重啟nginx服務

5、大功告成

image.png

二、子目錄配置

1、修改路由配置

加basename屬性(c1為子目錄名)


image.png

2、修改package.json

添加homepage行(后面加上子目錄c1!)


image.png

3、打包上傳

新建c1子目錄,把build文件夾里的內容上傳到子目錄文件夾中


image.png

4、nginx配置

重點:root和location

server {
  listen 80; #端口
  server_name xx.xx.xxx.xxx; #ip或域名 
  root /home/React/c1/; #文件夾目錄
  index index.html index.htm;
  location /c1/ {
      try_files $uri $uri/  /c1/index.html;
  }
  location ^~ /assets/ {
      gzip_static on;
      expires max;
      add_header Cache-Control public;
  }
  error_page 500 502 503 504 /500.html;
  client_max_body_size 20M;
  keepalive_timeout 10;
}
image.png

5、大功告成!

image.png
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容