Can I set up URL rewriting based on HTTP headers using .htaccess?

Yes, you can absolutely set up URL rewriting based on HTTP headers using .htaccess. Apache is mod_rewrite module provides this capability by allowing you to inspect request headers within a RewriteConddirective.

How It Works?

The key is the RewriteCond directive. You can access any HTTP request header using the syntax %{HTTP:Header-Name}. This lets you test the header is value before deciding whether a RewriteRule should be applied.

Practical Examples

Here are a few common scenarios where header-based rewriting is useful:

Example 1: Serving a Mobile Version Based on User-Agent.

This is a classic use case. You can redirect requests from mobile devices to a mobile-specific homepage.

RewriteEngine On
# Check if the User-Agent contains iPhone, Blackberry, or Android
RewriteCond %{HTTP_USER_AGENT} "(iPhone|Blackberry|Android)" [NC]
# If it matches, rewrite the root request to the mobile homepage
RewriteRule "^/$" "/homepage.mobile.html" [L]

Example 2: Custom Header-Based Routing.

If your application or a proxy sets a custom header (e.g., X-Route-To), you can use it to direct traffic to a specific backend script.

RewriteEngine On
# Check for a custom header value
RewriteCond %{HTTP:X-Route-To} "special" [NC]
# Rewrite the request to a special handler
RewriteRule "^api/(.*)$" "/special-handler.php?path=$1" [L,QSA]

Example 3: Referer-Based Control (Hotlink Protection).

You can block or redirect requests for images based on the Referer header, which is an HTTP header.

RewriteEngine On
# If the referer is not empty and not from your own domain
RewriteCond %{HTTP_REFERER} !^$
RewriteCond %{HTTP_REFERER} !^https?://(www.)?yourdomain.com [NC]
# Block access to image files (return 403 Forbidden)
RewriteRule .(gif|jpg|png)$ - [F,NC]

Key Points to Remember

Enable the Engine: Always ensure RewriteEngine Onis present at the top.

  • [NC] Flag: Use it for case-insensitive matching of header values.
  • [L] Flag: This tells Apache to stop processing further rules if this one matches.
  • Testing: Header values can be tricky. Test your rules thoroughly, perhaps using curl with custom headers (e.g., curl -H "X-Route-To: special" http://yoursite.com/api/test) to verify the behavior before deploying.

In short, using RewriteCond with %{HTTP:Header-Name} gives you a powerful way to make dynamic, context-aware routing decisions directly from your .htaccess file.

27 Views