Add Access Control Allow Origin Region(CORS) in NGINX?

Date Posted: 31-08-2017

In this post, we will explain on how to allow cors (Cross Origin Region) on nginx. We may have seen the following on google chrome console or firefox firebug addon.

No ‘Access-Control-Allow-Origin’ header is

Prerequisites:

  1. Nginx Webserver.  If nginx is not installed, follow the posts.
    1. Ubuntu 16.04
    2. Centos 7

Implementation:

If you followed the above posts, the default location of nginx configuration is /etc/nginx/sites-enabled/default.

Open nginx configuration and add the following lines inside location / section

vi /etc/nginx/sites-enabled/default

if ($request_method = 'GET') {
        add_header 'Access-Control-Allow-Origin' '*';
        add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
        add_header 'Access-Control-Allow-Headers' 'DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Content-Range,Range';
        add_header 'Access-Control-Expose-Headers' 'DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Content-Range,Range';
     }

The above code will allow access control region when the request is GET.

Verify the nginx syntax.

nginx -t

Restart the nginx service

systemctl restart nginx

 

Leave a Reply