Skip to content

Instantly share code, notes, and snippets.

@iki
Created September 15, 2019 20:12
Show Gist options
  • Star 13 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save iki/1247cd182acd1aa3ee4876acb7263def to your computer and use it in GitHub Desktop.
Save iki/1247cd182acd1aa3ee4876acb7263def to your computer and use it in GitHub Desktop.
Docker-compose nginx CORS proxy
version: '3.7'
services:
whoami:
image: jwilder/whoami
ports:
- 127.0.0.1:7000:8000
cors:
image: nginx:alpine
environment:
BACKEND: whoami:8000
ports:
- 127.0.0.1:8000:80
volumes:
- ./nginx-cors-proxy.conf:/etc/nginx/conf.d/default.template:ro
command:
- /bin/sh
- -c
- envsubst '$$BACKEND' < /etc/nginx/conf.d/default.template > /etc/nginx/conf.d/default.conf &&
exec nginx-debug -g 'daemon off;'
upstream backend {
server $BACKEND;
}
server {
listen 80 default_server;
listen [::]:80 default_server;
underscores_in_headers on;
server_name cors;
location / {
proxy_pass http://backend;
proxy_redirect http://$BACKEND http://$http_host;
proxy_read_timeout 300;
client_max_body_size 500M;
proxy_set_header Proxy '';
proxy_set_header Host $host;
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;
proxy_hide_header Access-Control-Allow-Origin;
proxy_hide_header Access-Control-Allow-Credentials;
set $CORS_CREDS true;
set $CORS_ORIGIN $http_origin;
set $CORS_METHODS 'GET, POST, PUT, DELETE, OPTIONS';
set $CORS_HEADERS 'Authentication-Token, Cache-Control, Cookie, If-Modified-Since, Range, User-Agent, X-Requested-With';
# FYI: Always allowed headers: Accept, Accept-Language, Content-Language, Content-Type
set $CORS_EXPOSE_HEADERS 'Content-Disposition, Content-Length, Content-Range, Set-Cookie';
# FYI: Always exposed headers: Cache-Control, Content-Language, Content-Type, Expires, Last-Modified, Pragma
set $CORS_PREFLIGHT_CACHE_AGE 600;
set $X_FRAME_OPTIONS '';
# set $X_FRAME_OPTIONS "ALLOW FROM $http_origin";
if ($request_method = 'OPTIONS') {
add_header Access-Control-Allow-Origin $CORS_ORIGIN;
add_header Access-Control-Allow-Methods $CORS_METHODS;
add_header Access-Control-Allow-Headers $CORS_HEADERS;
add_header Access-Control-Allow-Credentials $CORS_CREDS;
add_header Access-Control-Max-Age $CORS_PREFLIGHT_CACHE_AGE;
add_header Content-Type 'text/plain; charset=utf-8';
add_header Content-Length 0;
return 204;
}
if ($request_method != 'OPTIONS') {
add_header Access-Control-Allow-Origin $CORS_ORIGIN;
add_header Access-Control-Allow-Methods $CORS_METHODS;
add_header Access-Control-Allow-Headers $CORS_HEADERS;
add_header Access-Control-Allow-Credentials $CORS_CREDS;
add_header Access-Control-Expose-Headers $CORS_EXPOSE_HEADERS;
add_header X-Frame-Options $X_FRAME_OPTIONS;
}
}
}