Django配置中INTERNAL_IPS与ALLOWED_HOSTS是什么?用途及未使用影响
Alright, let's break down these two key Django settings clearly—they’re important for both security and debugging workflows.
ALLOWED_HOSTS
What it is
ALLOWED_HOSTS is a list of strings representing host/domain names that your Django application is allowed to serve. This includes things like example.com, www.example.com, or IP addresses like 192.168.1.100.
What it does
Its core job is to prevent HTTP Host header attacks. Attackers can forge the Host header in a request to trick your server into generating malicious links or exposing sensitive data. Django checks every incoming request's Host header against this list—if it doesn’t match an entry, the server rejects the request outright.
In DEBUG=True mode (local development), Django automatically allows localhost, 127.0.0.1, and [::1] even if ALLOWED_HOSTS is empty. But this safety net disappears when you switch to DEBUG=False (production).
What happens if you don’t configure it
- Production environment (
DEBUG=False): Django will return a400 Bad Requesterror for every incoming request. This is a hard security guardrail—you must setALLOWED_HOSTSto your actual domain/IPs before deploying to production. - Development environment: You might not notice issues at first since Django auto-whitelists local addresses, but it’s still good practice to set it explicitly (e.g.,
["localhost", "127.0.0.1"]) to mirror production setup and avoid surprises later.
INTERNAL_IPS
What it is
INTERNAL_IPS is a list of IP addresses that are considered part of your "internal" network—think your local development machine, office servers, or other trusted internal systems.
What it does
It’s primarily used to enable debugging tools and restrict sensitive debug information to trusted users. For example:
- The Django Debug Toolbar only loads if the request comes from an IP in
INTERNAL_IPS. - Some third-party libraries or custom code might use this setting to show detailed error pages or bypass certain security checks only for internal users (though you should be cautious with that last part).
Unlike ALLOWED_HOSTS, this setting doesn’t affect basic request handling—it’s purely for debug and internal tooling purposes.
What happens if you don’t configure it
- Debug tools like the Django Debug Toolbar won’t appear, even in
DEBUG=Truemode, because they default to only serving internal IPs. - If your app has custom logic tied to
INTERNAL_IPS(like showing admin-only debug info to your team), that logic won’t trigger for your local machine or internal servers. - For production environments, leaving
INTERNAL_IPSempty is totally fine—you shouldn’t be exposing debug tools there anyway.
内容的提问来源于stack exchange,提问作者Ashok Ramesh

