xccjk / x-blog

学习笔记
17 stars 2 forks source link

前端项目(react)部署到服务器 #60

Closed xccjk closed 1 year ago

xccjk commented 3 years ago

项目开发部署流程

  1. 创建项目开发
  2. 开发完成后,对项目进行打包
  3. 上传打包文件到服务器指定目录
  4. 配置nginx进行转发即可

以react项目为例

// 项目打包,生成build或者dist文件
npm run build

通过ftp之类的工具把打包后的文件上传到服务器指定目录即可。常见的scp(linux), Filezilla(windows)

打包后的文件放在了服务器的/www/wwwroot/目录下,最终的访问路径为/www/wwwroot/build/index.html

// nginx配置如下

server
{
    listen 5000;
    server_name 120.53.247.128;
    index index.php index.html index.htm default.php default.htm default.html;
    root /www/wwwroot/build/;
    autoindex on;

    location / {
        # root   /www/wwwroot;
        alias /www/wwwroot/build/;
        index index.html index.htm;
        #rewrite /config  /www/wwwroot/build/index.html;
        try_files $uri $uri/ /index.html;
     }

     location /api {
        proxy_pass http://.baidu.com;
     }

    #SSL-START SSL相关配置,请勿删除或修改下一行带注释的404规则
    #error_page 404/404.html;
    #SSL-END

    #ERROR-PAGE-START  错误页配置,可以注释、删除或修改
    #error_page 404 /404.html;
    #error_page 502 /502.html;
    #ERROR-PAGE-END

    #PHP-INFO-START  PHP引用配置,可以注释或修改
    include enable-php-00.conf;
    #PHP-INFO-END

    #REWRITE-START URL重写规则引用,修改后将导致面板设置的伪静态规则失效
    include /www/server/panel/vhost/rewrite/120.53.247.128.conf;
    #REWRITE-END

    #禁止访问的文件或目录
    location ~ ^/(\.user.ini|\.htaccess|\.git|\.svn|\.project|LICENSE|README.md)
    {
        return 404;
    }

    #一键申请SSL证书验证目录相关设置
    location ~ \.well-known{
        allow all;
    }

    location ~ .*\.(gif|jpg|jpeg|png|bmp|swf)$
    {
        expires      30d;
        error_log /dev/null;
        access_log off;
    }

    location ~ .*\.(js|css)?$
    {
        expires      12h;
        error_log /dev/null;
        access_log off; 
    }
    access_log  /www/wwwlogs/120.53.247.128.log;
    error_log  /www/wwwlogs/120.53.247.128.error.log;
}

注意的点

  1. 端口号我这里设置的5000,需要在服务器的防火墙配置端口可访问

  1. 如果出现了配置完nginx后,出现了403,可能是需要设置一下autoindex属性

nginx配置后访问显示403

  1. 假如你服务器的IP为http://120.53.247.128/,但是你需要请求的服务器地址为http://www.baidu.com/api/getUserInfo,在本地开发的是同通过webpack proxy配置代理,在线上就需要配置一下nginx proxy_pass进行转发了
location /api {
      proxy_pass http://www.baidu.com;
 }
  1. 假如你的项目目录为/www/wwwroot/build/index.html,你在配置location时,就需要这样来配置。记住有时候配置为root /www/wwwroot/build/,刷新nginx后发现没有生效,这时候你可以试试alias来看看
location / {
        # root   /www/wwwroot/build/;
        alias /www/wwwroot/build/;
        index index.html index.htm;
        #rewrite /config  /www/wwwroot/build/index.html;
        try_files $uri $uri/ /index.html;
}