nginx部署react build静态资源以及解决刷新路由404 - Go语言中文社区

nginx部署react build静态资源以及解决刷新路由404


  • 准备环境:nginx-1.14.2 // node v12.16.1 // npm 6.13.4
  • 前端代码为react+typescript
"homepage": "../"
  • 在package.json文件中添加,保证build出来的资源引入正常,添加位置与version name平级

 将静态资源拖拽到htm文件夹替换,如下图

 

打开conf文件夹在nginx.conf文件夹中修改配置启动ip与端口,代码如下

  •  下面conf中try_files $uri /index.html;一句可以解决当前路由下 页面刷新出现404的问题,当前设置访问ip端口为http://127.0.0.1:8888/,下属conf可见配置信息

#user  nobody;
worker_processes  1;


events {
    worker_connections  1024;
}


http {
    include       mime.types;
    default_type  application/octet-stream;

    #log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
    #                  '$status $body_bytes_sent "$http_referer" '
    #                  '"$http_user_agent" "$http_x_forwarded_for"';

    #access_log  logs/access.log  main;

    sendfile        on;
    #tcp_nopush     on;

    #keepalive_timeout  0;
    keepalive_timeout  65;

    #gzip  on;

    server {
        listen 8888;#端口
        #listen [::]:80 default_server ipv6only=on;
        server_name 127.0.0.1:8888;#配置的访问ip端口

        #charset koi8-r;

        #access_log  logs/host.access.log  main;

        location / {
           root   html;
           index  index.html index.htm;
           try_files $uri /index.html; #加上这句解决react 当前路由下 刷新 报404的问题
       }
        location /api { #需要转发的api
            proxy_set_header Host $host;
            proxy_set_header X-Real-IP $remote_addr;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
            proxy_pass http://10.10.50.103:20001/kiali/api; # 转发地址
        }
        #error_page  404              /404.html;

        # redirect server error pages to the static page /50x.html
        #
        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root   html;
        }

}

 

  •  nginx命令行启动停止 重启
    start nginx //启动nginx
    nginx -s stop //快速停止
    nginx -s reload //重启
  •  启动nginx后,浏览器访问设置的对应ip端口即可

 

 

版权声明:本文来源CSDN,感谢博主原创文章,遵循 CC 4.0 by-sa 版权协议,转载请附上原文出处链接和本声明。
原文链接:https://blog.csdn.net/D_claus/article/details/106404902
站方申明:本站部分内容来自社区用户分享,若涉及侵权,请联系站方删除。
  • 发表于 2021-05-30 09:03:07
  • 阅读 ( 1856 )
  • 分类:Go Web框架

0 条评论

请先 登录 后评论

官方社群

GO教程

猜你喜欢