If you are using PythonAnywhere to host your Django application, you may encounter this issue: you can't redirect your domain with HTTPS from the naked version to the www version (e.g., from https://yourdomain.com/ to https://www.yourdomain.com/). This issue was recorded in my Google Search Console. Whenever I visit the naked version of the URL, I always get a 404 Not Found error, but the error page is not served from my Django application.
Example: Can't redirect URL in PythonAnywhere
I read the PythonAnywhere documentation, which states that GoDaddy only supports HTTP version redirects (see: Pythonanywhere Naked Domains). I am already using Cloudflare for SSL on my WordPress site. Cloudflare has an option to set page rules to redirect HTTP to HTTPS and from the non-www version to the www version. I implemented this, and it solved my problem.
You can easily integrate your PythonAnywhere site with Cloudflare.
First, download your site's DNS records from your domain name provider (mine is GoDaddy). Then, add a new site (free version) in Cloudflare and import the DNS file to your Cloudflare account.
Finally, add the Cloudflare name servers to your domain's nameservers.
Go to the Cloudflare website and log in to your account.
Click on the domain for which you want to enable SSL.
In the Cloudflare dashboard, click on the SSL/TLS tab in the menu.
4. For the best security, choose Full (strict) if you have an SSL certificate on your server. If not, choose Flexible temporarily.
To set up a redirect from the non-www version to the www version of your domain using Cloudflare's Page Rules, follow these steps:
Go to the Cloudflare website and log in to your account.
Click on the domain for which you want to set up the redirect.
Go to Page Rules:
Click on Create Page Rule.
Set Up the Rule:
Add a Second Rule for HTTPS:
Click Save and Deploy for each rule you created.
Test the Redirects:
Step 4: Do this setting in your PythonAnywhere account and Django app
Turn off force HTTPS redirect in PythonAnywhere's "web apps" section
Configure Django Settings
In your Django settings, ensure that you have the following:
SECURE_SSL_REDIRECT = True # Redirect all HTTP to HTTPS SECURE_HOSTS = ['yourdomain.com', 'www.yourdomain.com'] # Add your domains
Ensure that your ALLOWED_HOSTS setting in your settings.py file includes both versions of your domain. It should look something like this:
ALLOWED_HOSTS = ['yourdomain.com', 'www.yourdomain.com']
That's all.
© 2024 Webapptiv. All rights reserved.