How to set CORS in Nginx server

CORS or Cross-Origin Resource Sharing is a protocol that will provide access resources to different domain. This is most commonly used for Javascript requests. The main use for CORS is to use CDN files like css, javascript or images load from different server.

In this article, we will discuss how you can allow CORS policy for Nginx server. This can be done through adding header Access-Control-Allow-Origin *. add_header option in Nginx server will add the new header to request.

So if you want all request set the header, you need to add the header in default Nginx config file. The default Nginx confinguration file located at /etc/nginx/nginx.conf. So lets edit file in nano editor.

sudo nano /etc/nginx/nginx.conf

And add the below option in the server key.

server {
    add_header Access-Control-Allow-Origin *;
}

Save and exit the file and restart the Nginx server.

sudo service nginx restart

That's it. Now every response will add the header Access-Control-Allow-Origin: *. To test it, run any site URL in Postman app and see the response header.

I hope you liked this article and help on your work.