21

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!

threejeez
  • 2,284
  • 6
  • 29
  • 50

1 Answers1

40

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
}
Mohammad AbuShady
  • 35,036
  • 9
  • 71
  • 86
  • should this work if I am testing on localhost? my domain on localhost is like example:8080 – Dariux Nov 27 '14 at 07:22
  • Yes, it should work just fine, you could also just set it to allow "*" and not worry about domain names – Mohammad AbuShady Nov 27 '14 at 07:31
  • its not working nor with domain not with * :( maybe this somehow does not reach this setting but I cannot think of how to check – Dariux Nov 27 '14 at 07:52
  • 1
    Check the response headers in the browser dev tools, both chrome and ff have that by default (usually by f12, check network tab) – Mohammad AbuShady Nov 27 '14 at 07:55
  • thanks, - I see the line "HTTP/1.1 301 Moved Permanently" and then in another line is "Location: https:// ..." So it is redirected. And not I will try to move on from there :) – Dariux Nov 27 '14 at 07:58
  • You should probably update your code, make it send the request to the new url (one in the location header) and do the same, check the returned headers and if it contains the allow access header – Mohammad AbuShady Nov 27 '14 at 08:05