nginx 部署单页react app 路由设置

今天要部署create react app 开发的网站,发现在页面中点击<Link to=""></Link>标签可以正常跳转。但是直接在路由中输入地址,进行非/路径的访问就会出错!!!

问题原因
直接将nginx 设置成静态容器,输入路由会被映射成web容器下的目录或是文件!!!

解决方案
在nginx.conf 中添加每一个前端路由的匹配,并把他们全部定位到index.html 上!

例子
假设有这样的前端路由,我们设置了/article, /uploadd, /login等六个界面
在这里插入图片描述
则其对应的nginx配置如下, (设我们把运行·build·以后./build里产生的内容,全部放在了/root/bookcloud/bookfront中)

## nginx 生产环境部署文件!!
user  root;
worker_processes  1;

#error_log  logs/error.log;
#error_log  logs/error.log  notice;
#error_log  logs/error.log  info;

pid        logs/nginx.pid;


events {
    worker_connections  1024;
}


http {
    include       /usr/local/nginx/conf/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;
    keepalive_timeout  65;


    server {
        # 监听端口80
        listen       80;  
        #设置项目根目录,也就是上面所打包的文件存放的文件目录
        root    /root/bookcloud/bookfront;
        index   index.html;

        #匹配html文件
        location ~* html {
               rewrite .* /index.html break;
        }
        location /login {
                rewrite .* /index.html break;
        }
        location /article {
                rewrite .* /index.html break;
        }
        location /personal {
                rewrite .* /index.html break;
        }
        location /uploadd {
                rewrite .* /index.html break;
        }
        location /classfiy {
                rewrite .* /index.html break;
        }
        location /admin {
                rewrite .* /index.html break;
        }
    }
}

还可能存在的问题
在项目开发中有可能之前在package.json配置过这个神奇的选项,这个选项虽然可以帮你在没有web容器的时后进行访问,但生产环境会导致部分图片无法正常访问,别忘了去掉!!
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值