WPCloud Deploy Documentation

CORS Example: Allow Access to Resources Between www and non-www Domains

Lets assume you have a site where certain requests are being made from https://yourdomain.com for resources on https://www.yourdomain.com.  And lets assume that, for some reason you do NOT want to issue a blanket redirect from one domain to another.  And lets also assume that the request to https://www.yourdomain.com is being denied because CORS is not configured to allow the cross-origin request.

What does your CORS entry in your /etc/nginx/sites-enabled/yourdomain.com file need to look like to enable this?

#Custom CORS rules for this site to allow for non www to request resources from www.
if ($http_origin ~* "^https?://(yourdomain.com|www.yourdomain.com)$") {
     set $cors_origin $http_origin;
}
add_header Access-Control-Allow-Origin $cors_origin;
#End custom CORS rules

This might seem needlessly complex. Why not just use add_headers with the www and non-www domains?

Because NGINX will only allow a SINGLE add_header directive for Access-Control-Allow-Origin.  Which does not work because you need to process requests from both www and non-www origins.

So, we use an IF statement to check the incoming origin and then set a variable (in this case $cors_origin) if the condition is satisfied.  Then, we use a single Access-Control-Allow-Origin to reference the URL set in the variable.  If the variable is empty, NGINX does not send a header.

WPCD Specific Considerations

Something specific to WPCD is this:  If you’re hoping to address media, js and other css files that are being cached in the browser, you need to add the CORS directive to the /etc/nginx/common/browsercache.conf file as well!

Why?

Because of an NGINX quirk.  The /etc/nginx/common/browsercache.conf file contains just one add_header directive to tell the browser to cache things.  But, because of this, NGINX will drop all the add_header directives in the parent SERVER{} block instead of inheriting them.  grrrr…it’s just something you need to be aware of and deal with.  And yes, this behavior is documented deep within the bowels of the NGINX documentation.

There could be several add_header directives. 
These directives are inherited from the previous configuration level if and only if 
there are no add_header directives defined on the current level.

 

Share: