Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.htaccess and params

i digg on the internet about .htaccess and rewrite rules i need to do with my site.

i saw something i dont understand and want to know what it means

i am wondering what is the difference between the 2 regular expression that i need to use for my site among all others i need to use):

RewriteRule ^home$ mainpage.php?id=$1 [QSA]

and

RewriteRule ^home(/)?$ mainpage.php?id=$1 [L]

i looked at the QSA and L but what the (/) means?

like image 953
Kevin Kelly Avatar asked Jan 03 '12 02:01

Kevin Kelly


2 Answers

The expression will be (/)? not (/). It means slash or not on the URL. These two URLs will go to the same place:

http://www.domain.com/home/

and

http://www.domain.com/home

So the slash is optional. This way, if a bot or a search engine puts it, the rule will work.

You can rewrite the rules like this:

RewriteRule ^home/?$ mainpage.php?id=$1 [L,QSA]

Also, I saw you said:

among all others i need to use

If all your pages goes to the same file (in this case mainpage.php), you can create one rule that will automatically rewrites them instead of creating 10 or 15 rules (or more). You can do this like this:

RewriteEngine on
REwriteBase /
RewriteRule ^([a-z0-9\-_]+)/?$ mainpage.php?id=$1 [L,QSA]

This rule will use Letters, Numbers, Dash and Underscores as the page.

like image 190
Book Of Zeus Avatar answered Nov 01 '22 07:11

Book Of Zeus


(/)? means "an optional slash".

  • (/) creates a group containing/matching whatever's between the parentheses. In this case, since it's a single character, the parentheses are more for capturing pieces than anything else. (Whatever matches will become $1, $2, etc depending on how many capture groups (sets of parentheses) there are in the pattern and where they are.)

BTW, your first RewriteRule doesn't make a whole lot of sense -- since there's no group to provide a value for $1, it'll probably always be blank. In the second, $1 will either be empty or a slash, depending on whether the subpattern matches. home will be rewritten to mainpage.php?id=, and home/ will be rewritten to mainpage.php?id=/.

  • The ? means "0 or 1 of the previous atom". ("Atoms", BTW, are the building blocks of a regex.) In this case, since the atom preceding it is (/) (which is effectively /), the ? means "0 or 1 slashes".
like image 42
cHao Avatar answered Nov 01 '22 08:11

cHao