How to enable CORS in Nginx for an Elixir Phoenix app?

I use Nginx as a proxy for my Elixir Phoenix app. Last week, I spent more than a day to figure out right configuration to enable CORS. This was in addition to using cors-plug Plug in the app.

If the URL is example.com and Phoenix app runs on the port 4000, you can create a configurtion file /etc/nginx/sites-enabled/example.com and add following configuration:

server {
  listen 80;
  server_name example.com www.example.com;

  add_header 'Access-Control-Allow-Credentials' 'true';

  location / {
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header Host $http_host;
    proxy_redirect off;
    proxy_pass http://localhost:4000;
    proxy_set_header Upgrade $http_upgrade;
    proxy_set_header Connection "upgrade";
    proxy_hide_header Access-Control-Allow-Origin;
    add_header Access-Control-Allow-Origin "$http_origin" always;
  }

(I tried almost all configurations available on StackOverflow and the one on enable cors website, but none of them worked for me.)

© 2023 Abhinav Saxena   •   Powered by Soopr   •   Theme  Moonwalk