Opened 9 years ago

Closed 9 years ago

Last modified 9 years ago

#12662 closed (wontfix)

Enforce Hostname Middleware

Reported by: robballou Owned by: nobody
Component: Uncategorized Version: 1.1
Severity: Keywords:
Cc: Triage Stage: Unreviewed
Has patch: yes Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: no UI/UX: no


For a recent project, I wanted to be able to enforce the hostname used in requests to a single domain (in this case, any requests like "" would redirect to ""). Rather than use the redirect app, I felt this was better suited to middleware like the PREPEND_WWW setting. So the following middleware will allow users to set an ENFORCE_HOSTNAME setting for a single or multiple hosts (string or list).

I wasn't sure how to submit a patch for the middleware itself, so that is just attached as a file. I did create tests for the middleware though.

Attachments (2) (1.2 KB) - added by robballou 9 years ago.
Middleware file
hostname_middleware.diff (3.7 KB) - added by robballou 9 years ago.
Test patch

Download all attachments as: .zip

Change History (4)

Changed 9 years ago by robballou

Attachment: added

Middleware file

Changed 9 years ago by robballou

Attachment: hostname_middleware.diff added

Test patch

comment:1 Changed 9 years ago by Russell Keith-Magee

Resolution: wontfix
Status: newclosed

I'm not sure I agree that the use case is common enough to warrant inclusion in Django's core. Adding www is a common redirection requirement; routing "" to "" isn't as common, and should probably be handled at the webserver level, anyway.

On top of that, you allow the user to specify a list of allowed hostnames, but if the submitted domain isn't in that list, it gets arbitrarily redirected to the first specified host. It strikes me that if you're in a situation where this sort of thing is an issue, configurability of the routing rules will be important.

In short - it strikes me as something that needs to be implemented on a per-site basis. The code isn't *that* complex, so this is probably better suited to a snippet than direct inclusion in core.

comment:2 Changed 9 years ago by robballou

I can understand the statements above, but there are two common issues (in my setups and probably for others):

  1. Most of the clients/web properties have "alternate" domains names for SEO and for other marketing. These often redirect back to the "primary" domain name. Also, part of making this middleware available is for the inverse of the PREPEND_WWW setting available (not all sites want their SEO/marketing to reflect a "www" domain).
  2. Many server/project setups do not allow easy web-server-level redirects at the host level in conjunction with Django projects. This may not be true for all setups, so it's demoted to a secondary concern!

Needless to say, the code is available and on GitHub if anyone needs it.

Note: See TracTickets for help on using tickets.
Back to Top