示例簡單配置如下:
server {
listen 8088;
server_name localhost;
location / {
root /home/demo/deploy/front/dist;
index index.html index.htm;
}
location /dev-api/ {
autoindex on;
client_max_body_size 100m;
proxy_pass https://xx.xx.xx.xx:1440/;
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root html;
}
}
上面 root 對應爲前段項目dist包部署位置, proxy_pass 爲對應的後端服務
上述配置在通過瀏覽器訪問時,進行刷新 或 訪問不錯在的路徑時會直接跳到Nginx的404頁面。
針對上面的情況只需要在Nginx添加一個try_files配置即可,如下:
location / {
root /home/demo/deploy/front/dist;
index index.html index.htm;
try_files $uri $uri/ /index.html;
}
try_files $uri $uri/ /index.html
try_files -嘗試訪問對應的資源,在第一個資源訪問不到時,訪問第二個資源,以次向後
$uri Nginx地址變量,即爲訪問的地址
若訪問url爲 http://www.xxx.com/index.html 則 $uri 爲 /index.html
$uri/ 表示一個目錄,請求訪問的目錄,Nginx try_files可自行判斷訪問目的的類型 是爲文件還是目錄
若訪問url爲 http://www.xxx.com/user/class/ 則 $uri/ 爲 /user/class/
所以以上配置的規則爲 當 $uri 和 $uri/ 均不是對應資源時 則返回 /index.html 頁面