Reputation: 1478
I don't quite understand the difference between specifying specific server blocks (1) vs setting restrictions on CORS (2).
i.e. If I want to restrict API calls only to domain1.com and domain2.com, which one of these should I opt for?
(1)
http {
index index.html;
server {
server_name www.domain1.com;
access_log logs/domain1.access.log main;
root /var/www/domain1.com/htdocs;
}
server {
server_name www.domain2.com;
access_log logs/domain2.access.log main;
root /var/www/domain2.com/htdocs;
}
}
(2)
set $cors '';
if ($http_origin ~ '^https?://(localhost|www\.domain1\.com|www\.domain2\.com)') {
set $cors 'true';
}
if ($cors = 'true') {
add_header 'Access-Control-Allow-Origin' "$http_origin" always;
...
Upvotes: 0
Views: 207
Reputation: 430
I'm a beginner with nginx, however, I think I can answer your question: it depends upon what you are trying to do.
(1) The server blocks determine if/how the web server handles a request based upon the domain requested. E.g. if the client requests domain1.com then the server will serve domain1.com resources; if the client requests domain2.com then the server will serve domain2.com resources; etc.
(2) The CORS code, as you've shown it, determines whether or not the server sends the browser a CORS ('Access-Control-Allow-Origin') header in the response (i.e. the header tells the browser whether or not it should send client requests only from the same domain or not). These are instructions for the client browser to implement CORS request restrictions (in my understanding) - they are not server-side implemented CORS restrictions.
So, if you want to have the client web browser "restrict api calls" then (2) is your best bet, whereas if you just want api calls for a specific domain to use specific code then (1) is your best bet. If, like me, you are looking to implement CORS restrictions on the server side, then neither of your options accomplish that and you must implement a different solution (but what you provide with (2) might be very helpful if used for determining whether or how to serve a response rather than send a CORS header to the browser). HTH.
Upvotes: 1