目前前端越來越多的採用Vue來進行開發,而Vue設計之初就是爲了方便前後端分離操作,當vue採用 History 模式如果僅以靜態文件方式部署是不支持刷新操作的,會報404異常問題,官方有詳細說明,具體請參見:https://router.vuejs.org/zh/guide/essentials/history-mode.html.
對於此的解決辦法官方也給出了說明,但過於簡單,在實際部署中還可能存在較多的問題,故而將在實際項目中的解決辦法予以發佈,僅其參考。
具體Nginx.conf配置如下:
# 啓動多worker進程
worker_processes auto;
events {
worker_connections 1024;
}
http {
include /etc/nginx/mime.types;
# 設置緩存信息
proxy_temp_path /tmp/temp_dir;
proxy_cache_path /tmp/cache levels=1:2 keys_zone=cache_one:100m inactive=1d max_size=1g;
# 配置springboot服務集羣
upstream seeker_server {
server service-XXXX-gateway-fat:7000 weight=3; #這裏的名稱爲K8s後端API服務名
server 192.168.2.103:7000 backup; #這裏backup表示爲備份服務器。
keepalive 32;
}
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"'
'"$upstream_cache_status"';
sendfile on;
keepalive_timeout 65;
# 啓用gzip壓縮
gzip on;
server {
listen 80;
# listen 443;
# ssl on;
# ssl_certificate /etc/nginx/ssl/server.crt;
# ssl_certificate_key /etc/nginx/ssl/server.key;
server_name localhost;
charset utf-8;
# 日誌輸出
# access_log /var/log/nginx/host.access.log main;
# nginx靜態文件緩存
location ~* ^.+\.(gif|jpg|jpeg|png|htm|html|css|js|flv|ico|swf|cur|gz|svg|map|mp4|ogg|ogv|webm)$ {
proxy_redirect off;
# 關閉靜態資源的訪問日誌
access_log off;
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_cache cache_one;
proxy_cache_key $host$uri$is_args$args;
proxy_cache_valid 200 302 1h;
proxy_cache_valid 301 1d;
proxy_cache_valid any 1m;
expires 7d;
add_header Nginx-Cache "$upstream_cache_status";
}
# vuejs靜態文件配置
location / {
root /etc/nginx/html;
try_files $uri $uri/ @router;
index index.html index.htm;
}
# 對應上面的@router,主要原因是路由的路徑資源並不是一個真實的路徑,所以無法找到具體的文件
# 因此需要rewrite到index.html中,然後交給路由在處理請求資源
location @router {
rewrite ^.*$ /index.html last;
}
# 反向代理springboot接口服務
location /xxxx/api/ {
# 解決springboot中獲取遠程ip的問題
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://seeker_server/gateway/xxxx/api/; #此處的seeker_server要和上述的upstream一致。
proxy_http_version 1.1;
proxy_set_header Connection "";
}
error_page 404 /404.html;
# redirect server error pages to the static page /500.html
#
error_page 500 502 503 504 /500.html;
location = /50x.html {
root /etc/nginx/html;
}
}
}
這裏的upstream可以直接寫成域名或IP都可以,同時還支持K8S環境下的後端項目的service名稱,這樣就自動實現了負載均衡,而無需再通過增加不同的機器IP來實現了。