Htaccess: Backreferences and multiple conditions and rules

Two rules I want to highlight today:

  1. Only the variables from the last-matched RewriteCond are available as back-references. 1)
  2. Conditions only apply to the very next rule. You’ll need to repeat the condition in order for it to apply to another rule. 2)

This came in handy when I was testing out the following rules for a Drupal htaccess. Basically, I wanted all the admin pages to be routed to the .com English version of the site. If the editor tried logging into, they would route to In the first example, I don’t have access to the HTTP_HOST backreference. It doesn’t matter in this case because i’m defining it in the rule. In the second and third rules, I’m repeating the condition so I can access the same back reference for two different rules.

    #keep admin pages on .com instance (uk only for now) (PROD)
    RewriteCond %{HTTP_HOST} ^(.*\.)?$ [NC]
    RewriteCond %{REQUEST_URI} ^/(uk)/(user|admin)/?(.*)? [NC]
    RewriteRule ^(.*)$ [R=301,L,NC]

    #keep admin pages on .com instance (uk only for now) (DEV / STAGE)
    RewriteCond %{HTTP_HOST} ^(dev|stg).example.(|de|fr|nl)$ [NC]
    RewriteRule ^uk/user/?(.*)?$1 [R=301,L,NC]
    RewriteCond %{HTTP_HOST} ^(dev|stg).example.(|de|fr|nl)$ [NC]
    RewriteRule ^uk/admin/?(.*)?$1 [R=301,L,NC]

References   [ + ]