1

I have the following statements in an .htaccess file

RewriteCond %{HTTP_HOST} ^myOldDomain\.com$ [NC]
RewriteRule  ^(.*)$ https://myNewDomaink.com/$1 [R=301,L]

It works fine. I basically found some sample code and modified it to my specific purpose. What I don't quite understand is:

Why does $1 refer to the the portion of the supplied url after the hostname - where is the documentation for this? There is no backreference in the RewriteCond.

2

2 Answers 2

1

$1 refers to everything the .*-regex matched to. In most cases this will be everything after the slash. You can test these queries on sites like Rubular.com and the numbers of the matches that are shown there, those are the numbers you can use as variables. You'll have to wrap those 'groups' in brackets to use them as variables.

2
  • Generally speaking with regexes, $0 refers to the entire match, and $1 would refer to the first backreference. My understanding, from reading the documentation, is that the backreference vars refer to backreferences in the last matched RewriteCond, which does not, in this case, contain any backreferences.
    – Scott
    Aug 13, 2013 at 17:41
  • 2
    The regex itself doesn't have to contain any backreferences. The part between the (first set of) parens is what will be in $1. Aug 14, 2013 at 1:55
1

After further reading and experimenting, it looks like the $1 is referencing the backreference from the RewriteRule. Since Rewrite rules and conditions default to the URI string, the Rewrite rule is saying:

Take the URI string and add it to the end of https://myNewDomainurl.com/

2
  • 1
    The relevant documentation is found here. They go into how the backreferences are constructed and referenced.
    – sysadmin1138
    Aug 14, 2013 at 21:34
  • @sysadmin1138 - thanks for the link. Until I saw the color coded representation my old eyes were not distinguishing between %N (percent sign N) variables which refer to RewriteCond backreferences, and $N (dollar sign N) variables which refer to RewriteRule backreferences. It's all making sense now.
    – Scott
    Aug 15, 2013 at 13:06

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .