设置nginx以允许子域的跨域请求

时间:2013-11-19 17:38:01

标签: nginx cross-domain

我有两个域名:

domain.com sub.domain.com

domain.com需要向sub.domain.com发出ajax请求。我意识到如果请求被硬编码为sub.domain.com,浏览器将阻止此操作。我尝试了以下nginx conf:

server {
    server_name domain.com;

    rewrite ^/api/(.*)$ http://sub.domain.com/api/$1; }

但是,我仍然在浏览器(Chrome)中收到以下错误:

No 'Access-Control-Allow-Origin' header is present on the requested resource.

如何设置nginx以指示浏览器允许domain.com和sub.domain.com之间的跨域请求?

谢谢!

1 个答案:

答案 0 :(得分:35)

我认为您需要在位置或服务器块内创建

server {
    server_name example.com;
    add_header Access-Control-Allow-Origin sub.example.com; # < this is the needed header
    # rest of the configuration
}
相关问题