猪小花1号2018-08-31 12:28作者:牛洋
1 问题背景
set $origin_host "";
set $is_cors "false";
set $cors_type "others";
if ($http_origin ~* ^https?://([a-zA-Z0-9\.]+)) {
set $origin_host $1;
}
if ($origin_host ~* ^[\w-]+\.kaola\.com(\.\w+)?(:\d+)?$) {
set $is_cors "true";
}
if ($origin_host = $host) {
set $is_cors "false";
}
if ($request_method = "OPTIONS") {
set $cors_type "options";
}
if ($is_cors = "false") {
set $cors_type "";
}
if ($is_cors = "true") {
add_header "Access-Control-Allow-Origin" "$http_origin";
add_header "Access-Control-Allow-Methods" "GET,HEAD,POST,PUT,DELETE,TRACE,OPTIONS,PATCH";
add_header "Access-Control-Allow-Headers" "Content-Type,X-Requested-With,ursAuth,origin,ursid, urstoken,x-test";
add_header "Access-Control-Allow-Credentials" "true";
add_header "Access-Control-Max-Age" "86400";
}
if ($cors_type = "options") {
return 204;
}
3.2 CORS拦截器改造
try {
// 从header获取origin
String origin = request.getHeader("Origin");
if (checkOrigin(origin) && !isProcessCorsByNginx(request)) {
response.setHeader("Access-Control-Allow-Origin", origin);
response.setHeader("Access-Control-Allow-Methods", "GET,HEAD,POST,PUT,DELETE,OPTIONS");
response.setHeader("Access-Control-Max-Age", "86400");
response.setHeader("Access-Control-Allow-Headers", "Content-Type,X-Requested-With,ursAuth,origin, ursid, urstoken");
response.setHeader("Access-Control-Allow-Credentials", "true");
}
// 如果是options请求则直接返回204
if (request.getMethod().equals(RequestMethod.OPTIONS.name())) {
response.setStatus(HttpStatus.NO_CONTENT.value());
return false;
}
} catch (Exception e) {
LogConstant.runLog.info("设置CROS信息异常", e);
}
return true;
private boolean isProcessCorsByNginx(HttpServletRequest request) throws MalformedURLException {
if (request == null || request.getRequestURL() == null) {
return false;
}
String requestUrl = request.getRequestURL().toString();
URL url = new URL(requestUrl);
String host = url.getHost();
return "huodong.kaola.com".equals(host);
}
网易云大礼包:https://www.163yun.com/gift
本文来自网易实践者社区,经作者牛洋授权发布。