Ad

Django And CORS Policy With Multiple Allowed Hosts

I have a small Django project running on a ubuntu server with NGINX and gunicorn.

Everything works great when users visit www.example.com, However, when a user visits example.com instead of www.example.com, this is where it falls apart. I am using some javascript with the fetch command, to get data from my API (Django REST) and it returns:

Access to fetch at 'https://www.example.com/builds/apidata/4' 
from origin 'https://example.com' has been blocked by CORS 
policy: No 'Access-Control-Allow-Origin' header is present on the requested 
resource. If an opaque response serves your needs, set the request's mode to 
'no-cors' to fetch the resource with CORS disabled.

The easiest solution I have found is to just remove example.com from my ALLOWED_HOSTS in my settings.py file, but then when users forget www. they will be greeted with a 404 error.

The CORS error message also states I can change the request mode, but I don't know the security implications of this..

I also tried to use redirection on my domain settings from example.com to www.example.com, but this doesn't seem work either.

Any suggestions would be appreciated!

Ad

Answer

Although you could certainly use CORS to allow this cross-domain usage, a simpler and cleaner solution is to just allow one root domain—either with www or not.

Setting PREPEND_WWW to True is a simple way to ensure that requests consistently use the www version, as it causes CommonMiddleware to issue redirects when the non-www version is used.

Ad
source: stackoverflow.com
Ad