django-allauth Google回调URL生产环境失效求助
Hey there, let's work through this Google login redirect issue with django-allauth in production—this is a common gotcha, so we can fix it step by step!
1. Verify the Django Sites Model Configuration
django-allauth relies heavily on Django's built-in Sites framework to generate correct redirect URLs. If your production setup is still redirecting to localhost, the active Site entry is almost certainly misconfigured:
- Log into your production Django admin panel.
- Navigate to Sites under the Sites section.
- Ensure there’s an entry where the
domain nameis set tomysite.com(match the display name if you want, but the domain is critical). - Confirm the
SITE_IDin your productionsettings.pymatches the ID of this correct Site entry. For example:SITE_ID = 2 # Replace with the ID of your mysite.com Site entry
If you don’t have the correct Site entry, create one first, then update SITE_ID accordingly.
2. Check ALLOWED_HOSTS in Production Settings
Django restricts which hosts can access your app via ALLOWED_HOSTS. If your domain isn’t listed here, it might fall back to default values that cause incorrect redirects:
ALLOWED_HOSTS = ['mysite.com', 'www.mysite.com'] # Include all domain variants you use
3. Double-Check Google OAuth Redirect URI
Small mismatches here are a frequent culprit:
- Make sure the URI uses
https://(Google requires secure connections for OAuth in production, so plain HTTP won’t work). - Confirm the URI ends with a trailing slash (
/) to match django-allauth’s callback path exactly. - Head to your Google Cloud Console OAuth 2.0 Client ID settings → Authorized redirect URIs and verify the entry is exactly:
https://mysite.com/accounts/google/login/callback/ - Note: Google’s settings can take 5-10 minutes to propagate, so wait a bit after updating before testing again.
4. Set ACCOUNT_DEFAULT_HTTP_PROTOCOL for HTTPS
Tell django-allauth to use secure URLs in production by adding this to your settings.py:
ACCOUNT_DEFAULT_HTTP_PROTOCOL = 'https'
5. Clear Caches and Restart Services
Stale cache can hold onto old configuration values:
- Restart your Django production server (e.g., Gunicorn, uWSGI) to apply all settings changes.
- Test in incognito mode or clear your browser’s cache/cookies to avoid cached redirects.
- If you’re using a caching layer (like Redis or Memcached) with Django, clear that cache too to remove stale Site or allauth data.
If none of these steps fix the issue, check your production server’s logs for errors related to django-allauth or OAuth callbacks—they’ll often give specific clues about why the redirect URL is still pointing to localhost.
内容的提问来源于stack exchange,提问作者rahul.m

