示例简单配置如下:
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 页面