400 字
2 分钟
部署前后端项目至Nginx服务器配置事项
部署前后端项目至Nginx服务器配置事项
1.跨域处理
:::tip 情景
出于网络安全,浏览器自带有跨域访问请求保护。在开发环境下我们在前后端配置了跨域处理。前端实际仅配置了请求地址,后端需要在CorsConfig跨域配置类中为请求源添加认证。
:::
(1)前端axios默认请求地址修改
默认开发环境下配置:
axios.defaults.baseURL = 'http://localhost:8080'
app.config.globalProperties.$axios = axios
部署配置:
axios.defaults.baseURL = '后端部署的地址,如http://175.24.164.23:8080'
app.config.globalProperties.$axios = axios
(2)后端跨域请求处理地址修改
添加前端部署的HTTP地址
private CorsConfigurationSource corsConfigurationSource() {
CorsConfiguration cors = new CorsConfiguration();
cors.addAllowedOriginPattern("http://175.24.164.155");
cors.addAllowedOriginPattern("http://www.iloveu1314.xyz");
cors.addAllowedOriginPattern("http://localhost:5173");
cors.setAllowCredentials(true);
cors.addAllowedHeader("*");
cors.addAllowedMethod("*");
cors.addExposedHeader("*");
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", cors);
return source;
}
2.服务端Nginx伪静态
:::tip 情景
因为我们开发的Vue是单页模式应用,从头至尾都停留在index.html上通过js实现内容变换。而nginx默认配置会寻找对应路由路径的html文件,故在不进行配置修改的情况下会报404。
:::
只需要在root节点后部署拦截重定向:
location / {
try_files $uri $uri/ @router;
#需要指向下面的@router否则会出现vue的路由在nginx中刷新出现404
index index.html index.htm;
}
#对应上面的@router,主要原因是路由的路径资源并不是一个真实的路径,所以无法找到具体的文件
#因此需要rewrite到index.html中,然后交给路由在处理请求资源
location @router {
rewrite ^.*$ /index.html last;
}
location /{
root /www/wwwroot/znzy/front/dist/;
index index.html index.htm;
try_files $uri $uri/ /index.html;
}