How to enable CORS on Nginx webserver for Magento REST API?

Maybe you will need this when develop/customize PWA POS on local machine.

Because your local origin URI is diffrent from your backend Magento REST API server, the browser may not allow you get resource from remote origin. In this case, you need enable CORS (Cross Origin Resource Sharing) in webserver

Step 1: Open your Magento backend nginx configuration file.
Step 2: Modify this file as follow

....
add_header 'Access-Control-Allow-Origin' $http_origin;
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS, PUT, DELETE, 
HEAD';
add_header 'Access-Control-Allow-Credentials' 'true';
add_header 'Access-Control-Allow-Headers' 'Origin,Content-Type,Accept,Authorization';

location / {
try_files $uri $uri/ /index.php$is_args$args;
    if ($request_method = 'OPTIONS') {
	add_header 'Access-Control-Allow-Origin' $http_origin;
	add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS, PUT, DELETE, HEAD';
	add_header 'Access-Control-Max-Age' '1728000';
	add_header 'Access-Control-Allow-Credentials' 'true';
	add_header 'Access-Control-Allow-Headers' 'Origin,Content-Type,Accept,Authorization';
	add_header 'Content-Type' 'text/plain; charset=UTF-8';
	add_header 'Content-Length' '0';
	return 204;
}
}
....

Step 3: Recheck NGINX config: nginx -t
Step 4: Reload nginx config: nginx -s reload to apply this change

Now you can use your backend magento site as Base API URI for PWA POS. :grin:
View the gist here.

3 Likes

Yeah, that’s a good way to make CORS working. But, if I have a theory model like

|| Docker container || <==> Nginx Reverse Proxy <==> || Internet ||

So, your configuration is actually not working! You can build the theory above and re-check for me?
Thank @craig

Which webserver you run inside the docker container?