Prevention of Host Header Injection in PHP – Easy Guide

When building web applications in PHP, security is very important. One common but less-known attack is Host Header Injection.

In this attack, a hacker changes the Host header in the HTTP request to trick your application.

  • This can lead to redirects to malicious sites,
  • Password reset links going to attacker’s site,
  • Or even bypassing security checks.

In this guide, we’ll learn what Host Header Injection is and how to prevent it in PHP.

What is Host Header Injection?

The Host header comes from the browser and tells the server which domain the user is visiting.

Example request:

GET /index.php HTTP/1.1
Host: example.com

But attackers can manipulate it:

GET /index.php HTTP/1.1
Host: evil.com

If your PHP code trusts $_SERVER['HTTP_HOST'] without validation, it may generate links or redirects using the wrong host.

Why is it Dangerous?

  • Password reset links could point to attacker’s domain.
  • CSRF protection tokens may be bypassed.
  • Redirection attacks could send users to fake login pages.

How to Prevent Host Header Injection in PHP

a) Never trust $_SERVER['HTTP_HOST'] directly

Instead, use a fixed trusted domain when generating absolute URLs.

Bad example :

// Dangerous - attacker can change Host header
$url = "https://" . $_SERVER['HTTP_HOST'] . "/reset-password";

Safe example:

// Use a fixed domain
$url = "https://example.com/reset-password";

b) Whitelist allowed domains

If you need to support multiple domains, create a whitelist and check against it.

$allowed_hosts = ['example.com', 'www.example.com'];

$host = $_SERVER['HTTP_HOST'] ?? '';

if (!in_array($host, $allowed_hosts, true)) {
  // Invalid host - reject request
  header("HTTP/1.1 400 Bad Request");
  exit("Invalid Host Header");
}

c) Use $_SERVER['SERVER_NAME'] or Config Variables

Instead of relying on user input, configure your app with a known domain in config.php:

define('APP_URL', 'https://example.com');

Then always build links like:

$url = APP_URL . "/dashboard";

d) Configure Web Server Security

At the Apache/Nginx level, you can reject unknown host headers.

Apache example:

<VirtualHost *:80>
  ServerName example.com
  ServerAlias www.example.com
  UseCanonicalName On
</VirtualHost>

Nginx example:

server {
  listen 80;
  server_name example.com www.example.com;
  return 444;
}

Best Practices

  • Always use absolute URLs with a trusted domain.
  • Block or redirect requests with invalid host headers.
  • Log suspicious requests for monitoring.
  • Apply security headers like Content-Security-Policy to reduce attack impact.

Conclusion

Host Header Injection may not be as famous as SQL Injection, but it can be very dangerous in PHP applications.
The rule is simple:

Never trust $_SERVER['HTTP_HOST'] directly
Always use a fixed domain or whitelist

By following these simple steps, your PHP application will be much safer from Host Header Injection attacks.