CORS stands for Cross-Origin Resource Sharing. It’s a mechanism that allows browsers to request resources from a different domain from the one they are currently on, such as fonts, scripts, images, etc.
CORS requires the server to send some headers that indicate which domains are allowed to access the resources, and what methods and headers are supported.
To configure NGINX for CORS in RunCloud, follow these steps:
- Log in to your RunCloud dashboard and select the server that has the web application that you want to enable CORS for.
- Click on “Web Application” from the main navigation menu and then click on the web application that you want to enable CORS for.
- Click on “NGINX Config” from the sub-navigation menu and then click on “Add a New Config“.
- Choose location.root as the type of config and enter a name for your config file, such as
cors
. - Add the following code to the config file:
if ($request_method = 'OPTIONS') {
add_header 'Access-Control-Allow-Origin' '*';
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
add_header 'Access-Control-Allow-Headers' 'DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range';
add_header 'Access-Control-Max-Age' 1728000;
add_header 'Content-Type' 'text/plain; charset=utf-8';
add_header 'Content-Length' 0;
return 204;
}
if ($request_method = 'POST') {
add_header 'Access-Control-Allow-Origin' '*' always;
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS' always;
add_header 'Access-Control-Allow-Headers' 'DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range' always;
add_header 'Access-Control-Expose-Headers' 'Content-Length,Content-Range' always;
}
if ($request_method = 'GET') {
add_header 'Access-Control-Allow-Origin' '*' always;
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS' always;
add_header 'Access-Control-Allow-Headers' 'DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range' always;
add_header 'Access-Control-Expose-Headers' 'Content-Length,Content-Range' always;
}
This code will enable CORS for your web application by sending the appropriate headers for different request methods. You can customize the values of the headers according to your needs. For example, you can change the ‘*’ to a specific domain name if you want to restrict the access to only that domain.
Click on “Save Config” and then click on “Reload NGINX“. Now, your web application should be able to handle CORS requests from different domains without any errors.