NGINX Reverse Proxy and CORS

Luis Bocchi
2 min readOct 27, 2020

--

“After dealing with a CORS problem finally i got a configuration that works, so i will share with you…”

This is the definitive “configuration” to fix CORS problems in your Reverse Proxy Environment.

This Wide Open configuration that sets all the necesary headers to avoid the CORS problems, finally pass the control to a balancer where you can add more instances of your App using 4001 and 4002 internal ports

Copy this configuration into the configuration file of your site, be careful with your certificate configuration, because in this example i am using Certbot, but may be you have other configuration.


upstream app {
server 127.0.0.1:4001;
server 127.0.0.1:4002;
}
server {listen 80;
listen [::]:80;
listen 443 ssl;
listen [::]:443 ssl ipv6only=on;
server_name my.domain.com;

location / {

proxy_set_header 'Access-Control-Allow-Origin' '*';

proxy_set_header 'Access-Control-Allow_Credentials' 'true';
proxy_set_header 'Access-Control-Allow-Headers' 'Authorization,Accept,Origin,DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Sinc$proxy_set_header 'Access-Control-Allow-Methods' 'GET,POST,OPTIONS,PUT,DELETE,PATCH';proxy_pass http://app;proxy_http_version 1.1;proxy_set_header Connection 'upgrade';
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Host $host;
proxy_set_header X-NginX-Proxy true;
proxy_cache_bypass $http_upgrade;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot
ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot
ssl_certificate /etc/letsencrypt/live/my.domain.com/fullchain.pem; # managed by Certbot
ssl_certificate_key /etc/letsencrypt/live/my.domain.com/privkey.pem; # managed by Certbot
}
server {
if ($host = my.domain.com) {
return 301 https://$host$request_uri;
} # managed by Certbot
if ($host = domain.com) {
return 301 https://$host$request_uri;
} # managed by Certbot
return 404; # managed by Certbot
}

--

--

Luis Bocchi
Luis Bocchi

Written by Luis Bocchi

Entrepreneur, Blockchain enthusiast, some knowledge of it and many years of programming