./conf/cors/<site-name> Configuration Assuming that site-name is webapplicationconsultant.com and I want to enable credentials for varunbatra.com along it itself" /> ./conf/cors/<site-name> Configuration Assuming that site-name is webapplicationconsultant.com and I want to enable credentials for varunbatra.com along it itself" />

Enable CORS with Credentials in Nginx

You must have noticed that when enable cors with “*”, it doesn’t allow credential to pass. Solution to this is pretty simply, you just need to list all of your domains in configuration. My approach is to have a separate file for each domain.

Directory Structure:

./conf/site-enabled/<site-name>
./conf/cors/<site-name>

Configuration

Assuming that site-name is webapplicationconsultant.com and I want to enable credentials for varunbatra.com along it itself – This is how it goes:

#./conf/cors/webapplicationconsultant.com


set $cors '';
if ($http_origin ~ '^https?://(varunbatra\.com|webapplicationconsultant\.com)') {
        set $cors 'true';
}

if ($cors = 'true') {
        add_header 'Access-Control-Allow-Origin' "$http_origin" always;
        add_header 'Access-Control-Allow-Credentials' 'true' always;
        add_header 'Access-Control-Allow-Methods' 'GET, POST, PUT, DELETE, OPTIONS' always;
        add_header 'Access-Control-Allow-Headers' 'Accept,Authorization,Cache-Control,Content-Type,DNT,If-Modified-Since,Keep-Alive,Origin,User-Agent,X-Requested-With' always;
        # required to be able to read Authorization header in frontend
        #add_header 'Access-Control-Expose-Headers' 'Authorization' always;
}

if ($request_method = 'OPTIONS') {
        # Tell client that this pre-flight info is valid for 20 days
        add_header 'Access-Control-Max-Age' 1728000;
        add_header 'Content-Type' 'text/plain charset=UTF-8';
        add_header 'Content-Length' 0;
        return 204;
}
#./conf/site-enabled/webapplicationconsultant.com

server {
	listen 443 ssl;
	server_name webapplicationconsultant.com;
....	
        location / {
                include "./../cors/webapplicationconsultant.com";
                try_files $uri @app;
	}
	location @app {
...
	}
}

Enable CORS with Credentials in Nginx

6 thoughts on “Enable CORS with Credentials in Nginx

  1. nginx: [emerg] “add_header” directive is not allowed here in /etc/nginx/snippets/cors2:14

    That will not work. Nginx doesn’t allow if

Leave a Reply

Your email address will not be published. Required fields are marked *

Scroll to top