How do I rewrite URLs based on HTTP headers using .htaccess?

Rewrite URLs based on HTTP headers in .htaccess, you use Apache is mod_rewrite module. The core technique is to access the header is value using the %{HTTP:Header-Name} syntax within a RewriteCond (Rewrite Condition) directive, and then apply a RewriteRule if that condition matches.

The Basic Syntax

The general pattern looks like this:

RewriteEngine On
RewriteCond %{HTTP:Your-Header-Name} ^Your-Value$ [NC]
RewriteRule ^pattern-to-match$ /target-path [L]

  • RewriteCond %{HTTP:Your-Header-Name}: This checks the value of the specified request header. You can use any valid HTTP header name (e.g., User-Agent, Referer, or a custom one like X-Forwarded-Host).
  • [NC]: This flag makes the condition match case-insensitively, which is often useful for header values.
  • RewriteRule: This rule is only applied if the preceding condition(s) are true.

Practical Examples

Here are a few common scenarios where this technique is used.

1. Serving a Mobile Version (User-Agent).

This is a classic example from Apache is documentation. It checks if the User-Agent header indicates a mobile device and serves a different homepage.

RewriteEngine On
RewriteCond %{HTTP_USER_AGENT} "(iPhone|Blackberry|Android)" [NC]
RewriteRule "^/$" "/homepage.mobile.html" [L]

2. Custom Header Routing (e.g., behind a Proxy).

If your application or a reverse proxy sets a custom header, you can use it to route traffic. For instance, if a header X-Forwarded-Host doesn not match your main domain, you might redirect the request.

RewriteEngine On
RewriteCond %{HTTP:X-Forwarded-Host} !^yourdomain.com$ [NC]
RewriteRule ^(.*)$ https://yourdomain.com/$1 [R=301,L]

3. Referer-Based Control (Hotlink Protection).

You can block or redirect requests for images based on the Referer header. This example from Apache is docs prevents other sites from directly linking to your images.

RewriteEngine On
RewriteCond %{HTTP_REFERER} !^$
RewriteCond %{HTTP_REFERER} !www.example.com [NC]
RewriteRule .(gif|jpg|png)$ - [F,NC]

 

3 Views