Skip to content

Instantly share code, notes, and snippets.

@tomkersten
Created October 28, 2011 20:36
Show Gist options
  • Star 31 You must be signed in to star a gist
  • Fork 9 You must be signed in to fork a gist
  • Save tomkersten/1323477 to your computer and use it in GitHub Desktop.
Save tomkersten/1323477 to your computer and use it in GitHub Desktop.
Nginx config with CORS headers added globally (for application w/ Basic Auth)
upstream your-app {
# fail_timeout=0 means we always retry an upstream even if it failed
# to return a good HTTP response (in case the Unicorn master nukes a
# single worker for timing out).
server unix:/tmp/your_app.socket fail_timeout=0;
}
server {
listen 80;
server_name yourdomain.com;
root /some/directory/for/rails/app/public;
access_log /var/log/nginx/yourapp-access.log;
error_log /var/log/nginx/yourapp-error.log;
rewrite_log on;
location / {
# For CORS
if ($request_method = OPTIONS ) {
add_header Access-Control-Allow-Origin "http://localhost"; # <- needs to be updated
add_header Access-Control-Allow-Methods "GET, OPTIONS";
add_header Access-Control-Allow-Headers "Authorization"; # <- You may not need this...it's for Basic Auth
add_header Access-Control-Allow-Credentials "true"; # <- Basic Auth stuff, again
add_header Content-Length 0;
add_header Content-Type text/plain;
return 200;
}
proxy_pass http://your-app;
proxy_redirect off;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
client_max_body_size 10m;
client_body_buffer_size 128k;
proxy_connect_timeout 90;
proxy_send_timeout 90;
proxy_read_timeout 90;
proxy_buffer_size 4k;
proxy_buffers 4 32k;
proxy_busy_buffers_size 64k;
proxy_temp_file_write_size 64k;
index index.html index.htm;
}
# if the request is for a static resource, nginx should serve it directly
# and add a far future expires header to it, making the browser
# cache the resource and navigate faster over the website
location ~ ^/(images|javascripts|stylesheets|system)/ {
root /some/directory/for/rails/app/public;
expires max;
break;
}
#error_page 404 /404.html;
# redirect server error pages to the static page /50x.html
#
error_page 500 502 503 504 /50x.html;
}
@Meekohi
Copy link

Meekohi commented Aug 19, 2014

This doesn't look like it will work for simple CORS requests. You don't change Access-Control-Allow-Origin for simple GET requests that don't use the OPTIONS preflight mechanism. Am I missing something?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment