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.

Scott
  • 394
  • 2
  • 7
  • 18
  • possible duplicate of [Everything You Ever Wanted to Know about Mod\_Rewrite Rules but Were Afraid to Ask?](http://serverfault.com/questions/214512/everything-you-ever-wanted-to-know-about-mod-rewrite-rules-but-were-afraid-to-as) – dawud Aug 13 '13 at 19:07
  • 1
    It doesn't really explain it in there, I think... it does explain *everything* else though. – Falcon Momot Aug 14 '13 at 01:54

2 Answers2

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.

  • 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 '13 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. – Falcon Momot Aug 14 '13 at 01: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/

Scott
  • 394
  • 2
  • 7
  • 18
  • 1
    The relevant documentation is found [here](http://httpd.apache.org/docs/2.2/rewrite/intro.html). They go into how the backreferences are constructed and referenced. – sysadmin1138 Aug 14 '13 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 '13 at 13:06