原文:http://www.nginx.cn/4314.html
AJAX從一個域請求另一個域會有跨域的問題。那么如何在nginx上實現ajax跨域請求呢?要在nginx上啟用跨域請求,需要添加add_header Access-Control*指令。如下所示:
1
2
3
4
5
6
7
8
9
10
11
|
location /{
add_header 'Access-Control-Allow-Origin' 'http://other.subdomain.com';
add_header 'Access-Control-Allow-Credentials' 'true';
add_header 'Access-Control-Allow-Methods' 'GET';
...
...
the rest of your configuration here
...
...
}
|
釋如下:
第一條指令:授權從other.subdomain.com的請求
第二條指令:當該標志為真時,響應於該請求是否可以被暴露
第三天指令:指定請求的方法,可以是GET,POST等
如果需要允許來自任何域的訪問,可以這樣配置:
1
|
Access-Control-Allow-Origin: *
|
重啟nginx
1
|
service nginx reload
|
ajax跨域請求測試
成功時,響應頭是如下所示:
1
2
3
|
HTTP/1.1 200 OK
Server: nginx
Access-Control-Allow-Origin: other.subdomain.com
|