How to Enable CORS in NGINX

  1688 views   5 months ago Nginx

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.

Author : Harsukh Makwana
Harsukh Makwana

Hi, My name is Harsukh Makwana. i have been work with many programming language like php, python, javascript, node, react, anguler, etc.. since last 5 year. if you have any issue or want me hire then contact me on [email protected]