Skip to content

Redirect HTTP -> HTTPS for custom domains #6882

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
Closed
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 7 additions & 1 deletion readthedocs/proxito/middleware.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
import logging

from django.conf import settings
from django.shortcuts import render
from django.shortcuts import render, redirect
from django.utils.deprecation import MiddlewareMixin

from readthedocs.projects.models import Domain, Project
Expand Down Expand Up @@ -83,6 +83,12 @@ def map_host_to_project_slug(request): # pylint: disable=too-many-return-statem
project_slug = domain.project.slug
request.cname = True
log.debug('Proxito CNAME: host=%s', host)

if domain.https and not request.is_secure():
# Redirect HTTP -> HTTPS (302) for this custom domain
log.debug('Proxito CNAME HTTPS Redirect: host=%s', host)
return redirect('https://%s%s' % (host, request.get_full_path()))
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

we should use f-strings or .format here


return project_slug

# Some person is CNAMEing to us without configuring a domain - 404.
Expand Down
14 changes: 14 additions & 0 deletions readthedocs/proxito/tests/test_middleware.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,20 @@ def test_proper_cname(self):
self.assertEqual(request.cname, True)
self.assertEqual(request.host_project_slug, 'pip')

def test_proper_cname_https_upgrade(self):
domain = 'docs.random.com'
get(Domain, project=self.pip, domain=domain, https=True)

for url in (self.url, '/subdir/'):
request = self.request(url, HTTP_HOST=domain)
res = self.run_middleware(request)
self.assertIsNotNone(res)
self.assertEqual(res.status_code, 302)
self.assertEqual(
res['Location'],
f'https://{domain}{url}',
)

def test_proper_cname_uppercase(self):
get(Domain, project=self.pip, domain='docs.random.com')
request = self.request(self.url, HTTP_HOST='docs.RANDOM.COM')
Expand Down