Closed TeemuSuoranta closed 4 years ago
NGINX allows adding headers under the server
block with add_header
. You can include a CORS header in NGINX's default configuration file /etc/nginx/sites-available/default
by appending
vagrant@development:~$ sudo nano /etc/nginx/sites-available/default
server {
...
add_header Access-Control-Allow-Origin *;
...
}
What do you mean by adding NGINX configs that only apply to development environment?
Update: Apparently you can take care of preflight requests via PHP and I just was not passing the right CORS header (as there apparently are multiple all the sudden). For anyone having CORS issues, you should check Access-Control-Allow-Headers
and Access-Control-Allow-Methods
.
@sjaks That probably works but it unfortunately is nowhere in version control for other developers. I was thinking of the /nginx/
directory like example.conf
just that it can be in Git.
All in all, looks like I can do all I have to do via PHP and I'm no longer sure if there are other use cases for local only NGINX rules.
Thanks for the suggestion!
We could in theory extend our Nginx config to read files from path
nginx-$WP_ENV/*.conf
or nginx/*.conf-$WP_ENV
and then you could add a
file such as nginx/cors.conf-development
. However, experience has shown
that developers easily make mistakes with Nginx configs, as they are very
unforgiving and the developer experience, debugging tools, feedback etc
works much better when as much as possible is done in PHP.
If you got this working in PHP, you can for example have
htdocs/wp-content/mu-plugins/cors.php
with a if $WP_ENV == 'development'
and emit what you want. That would be a pretty clean
solution and easy for fellow developers to grasp.
Thanks for the tips. I think we can close this issue and come back to it if someone finds a real use case that actually do require NGINX rules locally.
It could be helpful for JS/React development to be able to add some NGINX configurations that apply only to development environment. Mainly CORS headers as JS tools often have their own devserver somewhere like
localhost:3000
and you often need to connect to website for API that is in domainsite.local
.This means that as a local developer I need more open CORS header settings than in production where React app and website are on same domain. Currently there are no way to limit nginx rules to only dev environment that I know of.
For GET type APIs you can of course use PHP's
header()
function to display the CORS header but that does not work with many POST type APIs as they cause preflight request to the server and that request does not reach PHP. This is not really an issue just with Seravo environment but generally CORS are an issue that cannot be completely solved with PHP and thus NGINX rules are needed.Solution: conf files with naming
something.conf.local
are loaded only while on Vagrant.