Django hostname middleware

Recently I wanted to enforce the hostname in a couple Django-based projects. By default, Django really only allows you to enforce that a “www” is present in the URL. To me this seems rather one-sided as several sites may need:

  • To enforce that the “www” is not present
  • Or that an alternate domain name resolves to the primary domain

So I created the following middleware to enforce hostnames and submitted it to be added to the core (which was rejected). But in case you need to enforce the domain that visitors to your projects use, you may find this to be handy!