Apache’s mod_rewrite & mod_proxy: Use “Reverse Proxy Request Headers” for rewrite rules

Imagine the following scenario:

  • The URL to your site is your-public-url.com (hosted in a low-priced web package that only supports reroutings to other URLs).
  • The “internal” URL to your site is your-internal-url.com (e.g. an DynDNS-URL to your home server).
  • The hoster of your-public-url.com uses apache’s mod_proxy that acts in a reverse proxy mode to redirect your-public-url.com to your-internal-url.com

If you now need a rewrite rules that matches against your (public) host name (your-public-url.com in this example) you will meet the problem, that the HTTP header “Host” is overwritten with “your-internal-url.com”.

Fortunately, mod_proxy adds the following additional http headers to the request that contains information about the origin server:

  • X-Forwarded-For: The IP address of the client.
  • X-Forwarded-Host: The original host requested by the client in the Host HTTP request header.
  • X-Forwarded-Server: The hostname of the proxy server.

Moreover, mod_rewrite supports the %{HTTP:header} expression to match against any HTTP header field (see RewriteCond Directive). In result you can use the following mod_rewrite condition to match against the hostname originally requested by the client:

RewriteCond %{HTTP:X-Forwarded-Host} your-public.url.com

Leave a comment

Your email address will not be published. Required fields are marked *

*