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
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 stringSo, 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
Rewritecond %{REQUEST_URI} !^/mySite
Check and make sure the requested uri does not("!") start with("^") "/mySite"
Rewriterule ^(.*)$ /mySite/web/app_dev.php
Then if that is true, take things starting with("^") any character(".") any amount of times("*") and send it to "/mySite/web/app_dev.php"
So a URI of /controller/site-action will be sent to that file while /mySite/css/style.css would not be.
Many places to check that will give a breakdown and explanation: http://regex101.com/
Regular expressions work character after character. In your `.htaccess it checks if the current URI matches the regex. In this image, follow the line character after character and it returns true:
^
and $
stand for the beginning and end of a string. .
allows any character and *
tells to "repeat the last rule as often as possible".