user3150060
user3150060

Reputation: 1745

what does $1 in .htaccess file mean?

I am trying to understand the meaning of this line in the .htaccess file

 RewriteRule ([a-z0-9/-]+).html $1.php [NC,L,QSA]

basically what does $1.php ? what file in the server

if we have home.html where this gonna redirect to? home.php?

Upvotes: 19

Views: 31102

Answers (4)

IMSoP
IMSoP

Reputation: 97718

.htaccess files can contain a wide variety of Apache configuration directives, but this one, like many, is to do with the URL rewriting module, mod_rewrite.

A RewriteRule directive has 3 parts:

  • a Pattern (regular expression) which needs to match against the current URL
  • a Substitution string, representing the URL to serve instead, or instruct the browser to redirect to
  • an optional set of flags

In this case, you have a regular expression which matches anything ending in .html which consists only of letters a-z, digits 0-9, / and -. However, it also contains a set of parentheses (...), which mark a part of the pattern to be "captured".

The Substitution string can then reference this "captured" value; the first capture is $1, and the second would be $2, and so on.

In this case, the captured part is everything before the .html, and the Substitution is $1.php, meaning whatever string came before .html is kept, but the .html is thrown away and .php is stuck on instead.

So for your specific example, accessing home.html will instead act as though you had requested home.php.

Upvotes: 5

user428517
user428517

Reputation: 4193

$1 is the first captured group from your regular expression; that is, the contents between ( and ). If you had a second set of parentheses in your regex, $2 would contain the contents of those parens. Here is an example:

RewriteRule ([a-z0-9/-]+)-([a-z]+).html$ $1-$2.php [NC,L,QSA]

Say a user navigates to hello-there.html. They would be served hello-there.php. In your substitution string, $1 contains the contents of the first set of parens (hello), while $2 contains the contents of the second set (there). There will always be exactly as many "dollar" values available in your substitution string as there are sets of capturing parentheses in your regex.

If you have nested parens, say, (([a-z]+)-[a-z]+), $1 always refers to the outermost capture (in this case the whole regex), $2 is the first nested set, and so on.

Upvotes: 24

zessx
zessx

Reputation: 68790

$1 refers to the first group caught by your regex (ie between parenthesis). In your case it refers to :

([a-z0-9/-]+)

For the URL mypage.html, $1 will contain "mypage", and the rule will redirect to mypage.php.

Upvotes: 2

AbraCadaver
AbraCadaver

Reputation: 78994

It's a reference to the first capture group denoted by the parentheses in the pattern ([a-z0-9/-]+).html$. If there were two (.*)-(.*) then you would access $1 for the first capture group and $2 for the second, etc...

Upvotes: 2

Related Questions