Adding CORS policy to local site

Hi Ben, thanks for the insights you presented. After a lot of trial and error - hours, in fact - I was able to figure out a way to do this within my development environment!

The reason CORS was not working was due to the port numbers, regardless if it was the same domain or not. So I did have to add the Access-Control-Allow-Origin header and assign the wildcard. But the questions that took me forever to figure out was “where” and “how.”

I kept trying to make location blocks like this: location / { … } or location ~ /wp-json/ { … } but that would result in 404 errors and 502 errors. I figured out that this wasn’t the right direction since nearly all of WordPress relies on the index.php file - duh! So that made me switch gears into the location block that was already set up for PHP files: location ~ .php$ { … }

Once I figured that out, I started playing around with the Enable CORS code that I had found earlier. Most of that was either not necessary or too restrictive, and I also kept running into issues where the AJAX preflight requests were being denied because for some reason it wasn’t seeing the ‘Access-Control-Allow-Origin’ ‘*’ header. So after much Googling and combining ideas, this is what I ended up putting at the bottom of the location ~ .php$ { … } block:

# allow CORS requests
if ($request_method = 'OPTIONS') {
	add_header 'Access-Control-Allow-Origin' '*' always;
	add_header 'Access-Control-Allow-Methods' '*' always;
	add_header 'Access-Control-Allow-Headers' '*' always;
	add_header 'Access-Control-Max-Age' 1728000;
	add_header 'Content-Type' 'text/plain; charset=utf-8';
	add_header 'Content-Length' 0;
	return 200;
}
if ($request_method = 'POST') {
	add_header 'Access-Control-Allow-Origin' '*' always;
	add_header 'Access-Control-Allow-Methods' '*' always;
	add_header 'Access-Control-Allow-Headers' '*' always;
}
if ($request_method = 'GET') {
	add_header 'Access-Control-Allow-Origin' '*' always;
	add_header 'Access-Control-Allow-Methods' '*' always;
	add_header 'Access-Control-Allow-Headers' '*' always;
}

The addition of the “always” at the end I assume ensures that these headers take priority in every request, almost like !important clause in CSS. This allowed all requests to work, including the AJAX preflight requests!

Is this ugly? Sure. Is it unsafe? Yes, and should only be used within the Local environment. It’s definitely not for production environments… But it works!

Thank you again for your assistance!

1 Like