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)https://www.webmasterworld.com/forum92/5888.htm
  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)http://serverfault.com/questions/264076/rewrite-conditions-backreferences-passed-to-all-rules

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 example.co.uk/uk/user, they would route to example.com/user. 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} ^(.*\.)?example.com$ [NC]
    RewriteCond %{REQUEST_URI} ^/(uk)/(user|admin)/?(.*)? [NC]
    RewriteRule ^(.*)$ https://www.example.com/%2/%3 [R=301,L,NC]

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

References   [ + ]