Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set up nginx to allow cross-domain request for subdomain

Tags:

I've got two domains:

domain.com sub.domain.com

domain.com needs to make an ajax request to sub.domain.com. I realize that the browser will block this if the request is hardcoded to be sub.domain.com. I tried the following nginx conf:

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

However, I still get the following error in the browser (Chrome):

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

How can I set up nginx to instruct the browser to allow cross domain requests between domain.com and sub.domain.com?

Thanks!

like image 479
threejeez Avatar asked Nov 19 '13 17:11

threejeez


People also ask

Does CORS apply to subdomain?

Yes you have to enable it. You have to send CORS allow headers from server side to your browser. This is because a subdomain counts as a different origin.


1 Answers

I think you need to create this inside the location or server block

server {     server_name example.com;     add_header Access-Control-Allow-Origin sub.example.com; # < this is the needed header     # rest of the configuration } 
like image 147
Mohammad AbuShady Avatar answered Oct 27 '22 06:10

Mohammad AbuShady