
技术分享1 分钟阅读
nginx跨域配置
nginx可以通过跨域资源共享(CORS)的方式解决跨域问题。主要有两种方式: 1. 简单请求:对于简单请求,只需在nginx配置文件中添加以下配置:
add_header Access-Control-Allow-Origin *;
add_header Access-Control-Allow-Methods 'GET, POST, OPTIONS';
add_header Access-Control-Allow-Headers 'DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type';
if ($request_method = 'OPTIONS') {
return 204;
}这个配置允许来自所有域(Access-Control-Allow-Origin *)的GET, POST, OPTIONS请求,并允许指定的请求头。并对OPTIONS预检请求直接返回204。 2. 复杂请求:对于复杂请求(如请求方式为PUT或DELETE,或者contentType为application/json),需要在响应中添加以下头:
Access-Control-Allow-Origin: http://example.com
Access-Control-Allow-Methods: PUT,DELETE,POST,GET,OPTIONS
Access-Control-Allow-Headers: DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type
Access-Control-Expose-Headers: *同时需要在Options预检请求相应中返回:
Content-Length: 0
Connection: keep-alive
Access-Control-Max-Age: 1728000这样就完成了nginx跨域配置,主要原理是: 1. 跨域请求首先发起OPTIONS请求(预检请求) 2. nginx根据配置返回200和相关Access-Control-Allow-*首部 3. 确认请求可跨域后,客户端发起真实请求 4. nginx根据配置返回Access-Control-Allow-*首部 5. 客户端接收到响应,跨域请求完成 通过这两种方式(简单/复杂),nginx可以解决大多数跨域场景下的问题。
完整的配置文件
server {
listen 80;
server_name api.example.com;
# 允许跨域的源
add_header Access-Control-Allow-Origin *;
# 允许的请求方法
add_header Access-Control-Allow-Methods 'GET, POST, OPTIONS';
# 允许的请求头
add_header Access-Control-Allow-Headers 'DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type';
# 跨域预检请求的存活期
add_header Access-Control-Max-Age 86400;
# 允许浏览器发送认证信息
add_header Access-Control-Allow-Credentials true;
# 缓存请求信息 一定时间
add_header Cache-Control max-age=86400;
location / {
proxy_pass http://127.0.0.1:8080;
}
# 处理OPTIONS请求
if ($request_method = OPTIONS ) {
add_header Content-Length 0;
add_header Content-Type text/plain charset=utf-8;
return 204;
}
}读者评论
评论会同步写入该文在 Notion 中的页面底部(与正文同页,便于管理)。
暂无评论,欢迎抢沙发。