Joe
Joe

Reputation: 16831

Is ALLOWED_HOSTS needed on Heroku?

From what I understand, ALLOWED_HOSTS does a check when DEBUG=False to prevent an attacker from pointing their own domain to your site.

It looks like Heroku's Custom Domains do the same thing.

So instead of adding a required ALLOWED_HOSTS variable in your app.json for the Heroku Button (since it feels redundant and is error-prone when you're in a hurry), can you set ALLOWED_HOSTS = ['*'] and allow Heroku to verify the requests are coming where they should instead?

Upvotes: 14

Views: 16052

Answers (2)

Two-Bit Alchemist
Two-Bit Alchemist

Reputation: 18467

Warning: Possibly Out of Date

The settings.py below represents the contents of Heroku's docs when this answer was originally written in 2015. While I am relatively sure the ALLOWED_HOSTS setting presented here is safe, please consult the up-to-date docs before copying any of the rest of these settings!

Original answer follows. See below for more information.


This is exactly what you are supposed to do, per Getting Started with Django on Heroku:

settings.py

# Parse database configuration from $DATABASE_URL
import dj_database_url
DATABASES['default'] =  dj_database_url.config()

# Honor the 'X-Forwarded-Proto' header for request.is_secure()
SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')

# Allow all host headers
ALLOWED_HOSTS = ['*']

# Static asset configuration
import os
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
STATIC_ROOT = 'staticfiles'
STATIC_URL = '/static/'

STATICFILES_DIRS = (
    os.path.join(BASE_DIR, 'static'),
)

2018 Update

The link above no longer works, as Heroku formats their Getting Started docs a bit differently these days, providing pre-built example repos rather than code samples in the docs. The current Python Getting Started Repo has ALLOWED_HOSTS = [], but also DEBUG = True, which according to the Django 2.1 docs triggers a special case where

ALLOWED_HOSTS =  ['localhost', '127.0.0.1', '[::1]']

Since DEBUG = True is not recommended or a good idea at all in production, the original recommendation in this answer still stands as a production-ready solution for a Heroku app. Be sure you read and understand Charlie Weems' brief answer before deciding what to do.

Full Disclosure: I have not built a production Heroku app in a recent version of Django. YMMV :)

Upvotes: 18

Charlie Weems
Charlie Weems

Reputation: 1750

Note that Heroku removed ['*'] from the getting started guide in December 2017.

I recommend setting ALLOWED_HOSTS = ['.herokuapp.com'].

Even though Heroku's domain service is providing this protection, specifying the setting will be a reminder to update the configuration if moved to another hosting service.

Upvotes: 22

Related Questions