0
0
Djangoframework~5 mins

ALLOWED_HOSTS configuration in Django

Choose your learning style9 modes available
Introduction

The ALLOWED_HOSTS setting tells Django which website addresses it can serve. It helps keep your site safe by blocking requests from unknown places.

When you want to make sure your Django site only responds to your real domain names.
When deploying your Django app to a server with a public domain or IP address.
When testing your site locally and you want to allow localhost or 127.0.0.1.
When you want to prevent hackers from sending fake requests to your site.
Syntax
Django
ALLOWED_HOSTS = ['example.com', 'www.example.com', 'localhost', '127.0.0.1']

Use a list of strings, each string is a domain or IP your site will accept.

Use 'localhost' or '127.0.0.1' for local testing.

Examples
Only allow requests from mywebsite.com.
Django
ALLOWED_HOSTS = ['mywebsite.com']
Allow requests only from your local machine for testing.
Django
ALLOWED_HOSTS = ['localhost', '127.0.0.1']
Allow all subdomains of example.com, like blog.example.com.
Django
ALLOWED_HOSTS = ['.example.com']
Allow requests from any host (not recommended for production).
Django
ALLOWED_HOSTS = ['*']
Sample Program

This simple Django view retrieves the host from the request. Django automatically checks if the host is in ALLOWED_HOSTS before the view is called.

Django
# In settings.py:
ALLOWED_HOSTS = ['localhost', '127.0.0.1']

from django.http import HttpResponse

def simple_view(request):
    host = request.get_host()
    return HttpResponse(f'Hello from {host}!')
OutputSuccess
Important Notes

Always set ALLOWED_HOSTS in production to avoid security risks.

Using ['*'] disables host header validation and is unsafe for live sites.

Remember to include all domain names and subdomains your site uses.

Summary

ALLOWED_HOSTS controls which domains your Django app will serve.

It protects your site from fake or malicious requests.

Set it carefully before deploying your app.