As you can imagine, there are some advantages and disadvantages of using CORS on your server as it does not protect against cross-domain-based attacks, including CSRF.
The purpose of this tutorial is to give you a quick rundown of how CORS works and how to enable it on an NGINX server.
Why Enable CORS?
NOTE: The same domain refers to a different protocol, a different domain name, or a different port.
Requests Using CORS
The most common request that uses CORS include:
- Web Fonts that are defined in @font-face with a web stylesheet.
- Images and videos drawn on the canvas using drawImage()
- WebGL textures
- CSS shapes drawn from images.
Those are some of the basic requests that require CORS to function properly. It is good to understand that there are more concepts about CORS beyond the scope of this tutorial.
Enable CORS on Nginx Server
Let us get to the main part of this tutorial. To enable CORS on NGINX, you need to edit the configuration file (located in /etc/nginx/nginx.conf or usr/local/nginx/conf or /usr/local/etc/nginx) and add the header.
The general syntax to add header directives in Nginx is as:
Step 1 – Edit Nginx configuration
Launch your favorite editor and open the Nginx configuration:
Step 2 – Add the header
In the server block of your Nginx configuration, enter the following entry.
add_header Access-Control-Allow-Origin *;
Step 3 – Save and Restart Nginx
Finally, save the configuration file and restart nginx.
Step 4 – Confirm CORS
Use cURL to confirm that CORS is enabled as:
This should give you an output as shown below:
That is the end of this tutorial. I hope it helped you achieve the goal of enabling CORS on your Nginx server.
Thank you for reading and sharing.