前提:使用react-router的BrowserRouter路由模式(單頁開發(fā)掐松,url切換時(shí)需要服務(wù)器始終返回index.html)
一、根目錄部署
1罢杉、修改package.json文件
添加"homepage" :"http://xxx.com/" #解決部署到服務(wù)器后刷新頁面出錯(cuò)的問題
image.png
2趟畏、項(xiàng)目根目錄執(zhí)行npm run bulid
image.png
3、將打包后在根目錄生成的build文件夾上傳到服務(wù)器
image.png
4滩租、ubuntu安裝nginx
- apt-get update #更新源
- apt-get install nginx #安裝nginx
- vim /etc/nginx/nginx.conf #修改配置文件
server {
listen 80; #端口
server_name xx.xx.xxx.xxx; #ip或域名
root /opt/React/build/; #文件夾目錄
index index.html index.htm;
location / {
try_files $uri $uri/ /index.html;
}
location ^~ /assets/ {
gzip_static on;
expires max;
add_header Cache-Control public;
}
error_page 500 502 503 504 /500.html;
client_max_body_size 20M;
keepalive_timeout 10;
}
image.png
- service nginx restart #重啟nginx服務(wù)
5赋秀、大功告成
image.png
二、子目錄配置
1律想、修改路由配置
加basename屬性(c1為子目錄名)
image.png
2猎莲、修改package.json
添加homepage行(后面加上子目錄c1!)
image.png
3技即、打包上傳
新建c1子目錄著洼,把build文件夾里的內(nèi)容上傳到子目錄文件夾中
image.png
4、nginx配置
重點(diǎn):root和location
server {
listen 80; #端口
server_name xx.xx.xxx.xxx; #ip或域名
root /home/React/c1/; #文件夾目錄
index index.html index.htm;
location /c1/ {
try_files $uri $uri/ /c1/index.html;
}
location ^~ /assets/ {
gzip_static on;
expires max;
add_header Cache-Control public;
}
error_page 500 502 503 504 /500.html;
client_max_body_size 20M;
keepalive_timeout 10;
}
image.png
5、大功告成身笤!
image.png