Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Excerpts from my nginx config which helped me to skip CORS issue where cross origin requests are not allowed
server {
# Nginx listens at this address, http://172.17.0.1:4321
listen 4321;
server_name 172.17.0.1;
# Nginx listens to this location when calls are made to http://172.17.0.1:4321/location1
location ~ /location1 {
# we could have set any server here, lets call this server 1.
proxy_pass http://172.17.0.1:1234;
# add a header for host, keep it same all across
proxy_set_header Host "172.17.0.1:4321";
add_header 'Access-Control-Allow-Origin' '*';
proxy_http_version 1.1;
proxy_redirect off;
proxy_set_header Connection "";
access_log /var/log/nginx/some-random-logfile1.log;
}
# Nginx listens to this location when calls are made to http://172.17.0.1:4321/location2
location ~ /location2 {
# we could have set any server here, lets call this server 2.
proxy_pass http://172.17.0.1:3000;
# add a header for host, keep it same all across
proxy_set_header Host "172.17.0.1:4321";
add_header 'Access-Control-Allow-Origin' '*';
proxy_http_version 1.1;
proxy_redirect off;
proxy_set_header Connection "";
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Host $server_name;
access_log /var/log/nginx/some-random-logfile2.log;
# cors headers
if ($request_method = 'OPTIONS') {
add_header 'Access-Control-Allow-Origin' '*';
add_header 'Access-Control-Allow-Credentials' 'true';
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';
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' '*';
add_header 'Access-Control-Allow-Credentials' 'true';
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';
}
if ($request_method = 'GET') {
add_header 'Access-Control-Allow-Origin' '*';
add_header 'Access-Control-Allow-Credentials' 'true';
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';
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment