Django checks hostnames and browser request origins to protect application requests. A production hostname or proxy change must preserve these checks while describing the real deployment.
IN THIS ARTICLE
Check access and requirements
Record the canonical public hostname, any separate frontend origin and the trusted proxy chain. Reproduce the failing request without disabling security middleware.
01 Configure Django hosts and CSRF origins behind HTTPS
Set
ALLOWED_HOSTSto the hostnames the application is intended to serve. Avoid a wildcard merely to silence an invalid-host error.For legitimate cross-origin browser submissions, configure the exact required
CSRF_TRUSTED_ORIGINSvalues, including their schemes. This is separate from allowing a hostname.Ensure templates and JavaScript submit CSRF tokens through the supported Django mechanism. Check cookie domain, path and HTTPS-only settings.
Configure proxy SSL recognition only when the proxy reliably strips or overwrites the relevant incoming header. The application must not trust a header supplied directly by arbitrary clients.
Restart the application with the corrected settings and test a new browser session through the public HTTPS address.
02 Example: allow one HTTPS frontend origin in Django
For a Django service at https://api.example.com receiving approved browser form requests from https://www.example.com, the host and CSRF origin lists answer different questions. Merge these example values into the appropriate production settings after confirming the real addresses.
ALLOWED_HOSTS = ['api.example.com']
CSRF_TRUSTED_ORIGINS = ['https://www.example.com']
SESSION_COOKIE_SECURE = True
CSRF_COOKIE_SECURE = True
The host list does not include a scheme, while the trusted origin does. Keep CSRF token handling in the frontend and preserve the application’s authentication. A separate API CORS policy may also be needed. Add proxy SSL recognition only when the trusted proxy overwrites the relevant header and the upstream listener is protected.
Expected result: A permitted submission succeeds over HTTPS, an unexpected Host is rejected, and a missing CSRF token still fails. Broad wildcard lists are not required to make the documented customer workflow function.
Check the HTTPS result
Test a login and a state-changing form. Confirm an unexpected Host header is rejected and that the proxy does not generate HTTP links for an HTTPS request.
Resolve setup problems
A CSRF failure after login may involve stale cookies, a missing token or an origin mismatch. Use the private rejection reason to choose the fix rather than adding increasingly broad trusted origins.
A common question
Are ALLOWED_HOSTS and CSRF_TRUSTED_ORIGINS interchangeable?
No. They address different parts of the request. A site may need a valid host entry while requiring no extra trusted CSRF origin when its forms use the same origin.