Skip to content

CORS reverse proxy

Brian Ballsun-Stanton edited this page Jun 2, 2021 · 2 revisions

see https://httptoolkit.tech/blog/how-to-debug-cors-errors/ for debugging tips

On NGINX, have /etc/nginx/cors/cors.conf:


	#https://gist.github.com/Stanback/7145487
	set $cors 'true';
	#if ($http_origin ~ '^https?://(localhost|testing\.3\.faims\.edu\.au)') {
	#        set $cors 'true';
	#}
 
	if ($cors = 'true') {
			add_header 'Brian' 'brian' always;
	        add_header 'Access-Control-Allow-Origin' "$http_origin" always;
	        add_header 'Access-Control-Allow-Credentials' 'true' always;
	        add_header 'Access-Control-Allow-Methods' 'GET, POST, PUT, DELETE, OPTIONS' always;
	        add_header 'Access-Control-Allow-Headers' 'Accept,Authorization,Cache-Control,Content-Type,DNT,If-Modified-Since,Keep-Alive,Origin,User-Agent,X-Requested-With' always;
	        # required to be able to read Authorization header in frontend
	        add_header 'Access-Control-Expose-Headers' 'Authorization' always;
	}

	if ($request_method = 'OPTIONS') {
			add_header 'Brian-options' 'preflight' always;

			add_header 'Access-Control-Allow-Origin' "$http_origin" always;
	        add_header 'Access-Control-Allow-Credentials' 'true' always;
	        add_header 'Access-Control-Allow-Methods' 'GET, POST, PUT, DELETE, OPTIONS' always;
	        add_header 'Access-Control-Allow-Headers' 'Accept,Authorization,Cache-Control,Content-Type,DNT,If-Modified-Since,Keep-Alive,Origin,User-Agent,X-Requested-With' always;
	        # required to be able to read Authorization header in frontend
	        add_header 'Access-Control-Expose-Headers' 'Authorization' always;

	        # Tell client that this pre-flight info is valid for 20 days
	        add_header 'Access-Control-Max-Age' 1728000;
	        add_header 'Content-Type' 'text/plain charset=UTF-8';
	        add_header 'Content-Length' 0;
	        return 204;
	}

(Note this is only for testing, since this basically lets everything through)

Then in the reverse proxy /etc/nginx/sites-avail/db.domain:

cat alpha.db.faims.edu.au 
server {
        client_max_body_size 20G;

        root /var/www/html;
        index index.html;

        server_name alpha.db.faims.edu.au;




# https://docs.couchdb.org/en/latest/best-practices/reverse-proxies.html
# https://enable-cors.org/server_nginx.html
        location / {


            include cors/cors.conf;


            proxy_pass http://10.70.80.8:5986;
            proxy_redirect off;
            proxy_buffering off;
            proxy_set_header Host $host;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
            proxy_set_header X-Forwarded-Ssl on;

        }


    listen 443 ssl; # managed by Certbot
    

}

Clone this wiki locally