7

I am confused about this rule:

RewriteCond %{HTTPS} !=on

RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301,QSA]

How is it possible that a caret can match the whole URL if it is a position anchor?

I cannot find any official statement that it is a catch all symbol.

bastelflp
  • 9,362
  • 7
  • 32
  • 67
Masi
  • 125
  • 1
  • 8

1 Answers1

10

The caret means looking at the beginning of a line.

The caret matches at the beginning without consuming a character. So even the empty string matches ^. The empty string also matches ^$ since it begins at index 0 and ends at index 0.

The caret matches because the regular expression only needs to be found somewhere in the URL. It doesn't need to match the whole URL.

Using exactly ^ as the regular expression allows for more performance, since typical regular expressions only compare the beginning of the URL and therefore don't need to look at every character of the URL.

Roland Illig
  • 40,703
  • 10
  • 88
  • 121
  • Thx a lot for your answer. But how can a caret match anything without a parttern definition like this: ^(.+) – Masi Dec 31 '16 at 10:03
  • Concerning your answer i would expect on this Site https://regex101.com/ that a caret should highlight everything. But it doesnt... – Masi Dec 31 '16 at 10:17
  • Do you have an idea why the tester does not highlight all lines when the regex is only a caret ? – Masi Dec 31 '16 at 11:15
  • 1
    @Masi A caret does not consume any character. It matches only _at a specific position_. That's why you get the dotted vertical line on regex101.com. – Roland Illig Dec 07 '18 at 20:43
  • Worth adding that `^` or “the beginning of the line” happens to be _after_ the leading slash, i.e. after the hostname and a slash (`www.example.com/`). See also https://stackoverflow.com/a/7068886/711006. – Melebius May 05 '21 at 07:27
  • @Melebius There is a subtle difference between `httpd.conf` and `.htaccess`. In `httpd.conf` the request URL includes the leading slash, while in `.htaccess` the path portion is removed. – Roland Illig May 06 '21 at 10:21