Enable CORS from nginx config

What is CORS

Cross-Origin resource sharing(CORS) is a mechanism to allow resources on webpage to be requested from another domain outside the origin domain over the HTTP headers which provide browsers and servers a way to request URLS.

Problems

if you got problem sending request from ajax POST,GET .. etc in example when you work with two different domain or in real production too
you should use this configuration from your nginx settings

here the example to enable cors on nginx config, put this on your nginx block config,

location ~ \.php$ {
		try_files $uri =404;
		fastcgi_split_path_info ^(.+\.php)(/.+)$;
		fastcgi_pass unix:/var/run/php/php5.6-fpm.sock;
		fastcgi_index index.php;
		fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
		include fastcgi_params;

		if ($http_origin ~* .*) { # yeah, for local development. tailor your regex as needed
		     set $cors "true";
		}

		# apparently, the following three if statements create a flag for "compound conditions"
		if ($request_method = OPTIONS) {
		    set $cors "${cors}options";
		}

		if ($request_method = GET) {
		    set $cors "${cors}get";
		}

		if ($request_method = POST) {
		    set $cors "${cors}post";
		}

		# now process the flag
		if ($cors = 'trueget') {
		    add_header 'Access-Control-Allow-Origin' "$http_origin";
		    add_header 'Access-Control-Allow-Credentials' 'true';
		}

		if ($cors = 'truepost') {
		    add_header 'Access-Control-Allow-Origin' "$http_origin";
		    add_header 'Access-Control-Allow-Credentials' 'true';
		}

		if ($cors = 'trueoptions') {
		    add_header 'Access-Control-Allow-Origin' "$http_origin";
		    add_header 'Access-Control-Allow-Credentials' 'true';

		    add_header 'Access-Control-Max-Age' 1728000; # cache preflight value for 20 days
		    add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
		    add_header 'Access-Control-Allow-Headers' 'Authorization,Content-Type,Accept,Origin,User-Agent,DNT,Cache-Control,X-Mx-ReqToken,Keep-Alive,X-Requested-With,If-Modified-Since';

		    add_header 'Content-Length' 0;
		    add_header 'Content-Type' 'text/plain charset=UTF-8';
		    return 204;
		}

comments powered by Disqus