今天要部署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容器的时后进行访问,但生产环境会导致部分图片无法正常访问,别忘了去掉!!