Nginx 实现AJAX跨域请求

默北 Nginx1 50,75125字数 635阅读2分7秒阅读模式

AJAX从一个域请求另一个域会有跨域的问题。那么如何在nginx上实现ajax跨域请求呢?要在nginx上启用跨域请求,需要添加add_header Access-Control*指令。如下所示:

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
...
...

}

注释如下:文章源自运维生存时间-https://www.ttlsa.com/nginx/how-to-allow-cross-domain-ajax-requests-on-nginx/

第一条指令:授权从other.subdomain.com的请求文章源自运维生存时间-https://www.ttlsa.com/nginx/how-to-allow-cross-domain-ajax-requests-on-nginx/

第二条指令:当该标志为真时,响应于该请求是否可以被暴露文章源自运维生存时间-https://www.ttlsa.com/nginx/how-to-allow-cross-domain-ajax-requests-on-nginx/

第三天指令:指定请求的方法,可以是GET,POST等文章源自运维生存时间-https://www.ttlsa.com/nginx/how-to-allow-cross-domain-ajax-requests-on-nginx/

如果需要允许来自任何域的访问,可以这样配置:文章源自运维生存时间-https://www.ttlsa.com/nginx/how-to-allow-cross-domain-ajax-requests-on-nginx/

Access-Control-Allow-Origin: *

重启nginx文章源自运维生存时间-https://www.ttlsa.com/nginx/how-to-allow-cross-domain-ajax-requests-on-nginx/

service nginx reload

ajax跨域请求测试

成功时,响应头是如下所示:文章源自运维生存时间-https://www.ttlsa.com/nginx/how-to-allow-cross-domain-ajax-requests-on-nginx/

HTTP/1.1 200 OK
Server: nginx
Access-Control-Allow-Origin: other.subdomain.com
文章源自运维生存时间-https://www.ttlsa.com/nginx/how-to-allow-cross-domain-ajax-requests-on-nginx/文章源自运维生存时间-https://www.ttlsa.com/nginx/how-to-allow-cross-domain-ajax-requests-on-nginx/
weinxin
我的微信
微信公众号
扫一扫关注运维生存时间公众号,获取最新技术文章~
默北
  • 本文由 发表于 24/09/2014 01:00:59
  • 转载请务必保留本文链接:https://www.ttlsa.com/nginx/how-to-allow-cross-domain-ajax-requests-on-nginx/
评论  1  访客  1
    • 匿名
      匿名 9

      啧啧啧

    评论已关闭!