docker-files
docker-files copied to clipboard
Set Access-Control-Allow-Origin header conditionally in nginx
For some weird reason the Access-Control-Allow-Origin: *
header did not work for me. I decided to set the headers in the PHP application by using the tuupola/cors-middleware
package. Unfortunately nginx does not seem to care if a specific header is already set which led to a situation where in my response I had the Access-Control-Allow-Origin
twice set. Chrome does not like that and complained with an error. As a quick fix I supplied a custom basic.conf
configuration and removed the cross-domain-insecure.conf
include.
Even though my quick fix works, I would love to see a configuration that would set the header only when it's not already set by the PHP application. However that does not seem to do easily with nginx, there's a whole blog post explaining why if is evil in nginx configuration.
One solutions seems to be to make use of the lua_nginx_module
. See https://stackoverflow.com/a/34295867 or https://stackoverflow.com/a/34295867 for an example. It might also be possible to make use of the map feature of nginx: https://serverfault.com/a/598106 - not sure though if that would work in this specific case.
Had this issue today, too. If the backend returns a 202 response Nginx does not add the header. So I've added a CORS middleware in the PHP backend which solved the problem for 202 responses but now I have the same duplicate header issue for other responses.
We should remove the CORS header from Nginx. What do you think @sandrokeil ?
If you don't like using a 3rd party middleware like tuupola/cors-middleware
in your default prooph stack, you could potentially do the exact same what you already do in Nginx in a middleware shipped with prooph. Maybe add a check to not add the header if the header already present :)
That way it's also more "visible" what is going on. It took me quite some time to figure out where the header got added last time I had the problem.
We can remove the CORS configuration from nginx if it‘s not working properly. Maybe we can also check if a CORS header is present.