Heroku 上是否需要 ALLOWED_HOSTS? [英] Is ALLOWED_HOSTS needed on Heroku?
问题描述
据我所知,ALLOWED_HOSTS
会在 DEBUG=False
时进行检查,以防止攻击者将自己的域指向您的网站.
From what I understand, ALLOWED_HOSTS
does a check when DEBUG=False
to prevent an attacker from pointing their own domain to your site.
看起来 Heroku 的 自定义域 做同样的事情.
It looks like Heroku's Custom Domains do the same thing.
因此,不要在 app.json
中为 Heroku Button(因为感觉多余,而且着急的时候容易出错),能不能设置ALLOWED_HOSTS = ['*']
并允许 Heroku 验证请求是否到达他们应该到达的地方?
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?
推荐答案
警告:可能已过期
下面的 settings.py
代表了 Heroku 文档的内容,这个答案最初是在 2015 年编写的.虽然我相对确定这里提供的 ALLOWED_HOSTS
设置是安全的,在复制任何其余设置!
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.
这正是您应该做的,根据 Heroku 上的 Django 入门:
This is exactly what you are supposed to do, per Getting Started with Django on Heroku:
# 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 更新
上面的链接不再有效,因为现在 Heroku 对其入门文档的格式略有不同,提供了预先构建的示例存储库而不是文档中的代码示例.当前的 Python 入门存储库有 ALLOWED_HOSTS = []
,还有 DEBUG = True
,根据 Django 2.1 文档 触发了一个特殊情况,其中
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]']
由于 DEBUG = True
在生产中不推荐或根本不是一个好主意,此答案中的原始建议仍然是 Heroku 的生产就绪解决方案应用程序.在决定做什么之前,请务必阅读并理解查理威姆斯的简短回答.
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.
完全披露:我没有在最新版本的 Django 中构建生产 Heroku 应用程序.YMMV :)
Full Disclosure: I have not built a production Heroku app in a recent version of Django. YMMV :)
这篇关于Heroku 上是否需要 ALLOWED_HOSTS?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!