Nginx configuration to enable CORS for mobile app API

posted in: Uncategorized | 0

We’ve been working on the Cash Expenses mobile app and building an API to a backend server. Developing this API in our local instance is as trivial as running Python Django’s server on port 8000. For production, we run the Python Django application using gunicorn for the WSGI server, and nginx for listening on the standard web port 80. While the API worked perfectly with the local instance, the API calls were failing when running on production. We traced the problem to our Nginx configuration.

In this case, the mobile apps are calling into the backend service without using Django’s cookie or session authentication; instead, we use Django Rest Knox for token authentication (Django REST Framework’s builtin token authentication should not be used because it is a unencrypted single token).

The Nginx configuration has to be configured to allow all of GET, POST, PUT, PATCH, and DELETE methods from a non-web client. The configuration is inspired by other developers posting their Nginx configurations in Github, and we’ve extended it here:

https://gist.github.com/rhfung/12fced0c159572f5207a2da5b6ecdab1