Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Understanding a simple regex

I am developing a Symfony2 PHP application. In my Wamp server, the application is stored in www/mySite/ and my index.php is www/mySite/web/app_dev.php. Because/ of that, I have URL like 127.0.0.1/mySite/web/app_dev.php

I wanted to change the path so I acces my index file just by typing 127.0.0.1. After some research, I figured out that writting this .htacces in the www folder works :

RewriteEngine on
Rewritecond %{REQUEST_URI} !^/mySite
Rewriterule ^(.*)$ /mySite/web/app_dev.php

The only problem is that I don't understand why. Does somebody explain it to me ? I don't really understand the two last line, and regex like ^(.*)$

Thanks

like image 213
user2108742 Avatar asked Apr 07 '26 07:04

user2108742


1 Answers

This is a simple regex indeed:

^(.*)$

Let's break it up:

  • ^ - begging of a string
  • ( and ) - capture group, used to match part of a string
  • . - any character
  • .* - any charactery any number of times
  • $ - end of a string

So, putting it all together, it means: "match any number of any characters". Later this matched part (part in parentheses) is replaced by /mySite/web/app_dev.php.

To explain regexes a little bit more we could imagine different regexes:

  • ^lorem.*$ - string starting with word "lorem" followed by any number of any characters
  • ^$ - an empty string
  • ^...$ - a string containing three characters.

Now, putting it all together - Apache's rewrite rules are usually built of two directives: RewriteCond and RewriteRule. The latter directive will affect only those requests which match the condition given in the RewriteCond. You can think of them as a "if-then" pair:

# the "if" part - if request URI does not match ^/mySite
Rewritecond %{REQUEST_URI} !^/mySite

# the "then" part - then rewrite it to "/mySite/web/app_dev.php"
Rewriterule ^(.*)$ /mySite/web/app_dev.php
like image 58
kamituel Avatar answered Apr 08 '26 19:04

kamituel



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!