使用nginx部署React项目

两种部署方式

一、部署在nginx根目录下

二、部署在nginx非根目录下

在package.json里添加 "homepage": ".",如下

  "homepage": ".",
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
 },

然后在添加 basename

import {createBrowserHistory} from "history";

const history = createBrowserHistory({basename: "/app"});
export default history

完成这两步后执行 yarn build 打包,生成build目录。

把build目录上传到服务器的某个目录,比如 /usr/local/var/www 目录下,
然后在nginx.conf里添加

location /app {
    alias /usr/local/var/www/build;
    index index.html;
    try_files $uri /app/index.html; # 始终返回index.html
} 

执行 nginx -s reload 刷新,在页面打开 http://153.100.71.119/app,即可访问页面。

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容