Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does .htaccess work?

I'm trying to make my website display the other pages as a www.example.com/pageone/ link instead of www.example.com/pageone.html.

Problem is, i'm reading up on ways to do that using .htaccess and its getting me confused because i don't understand the commands.

I understand that the first step, however, is to write this in the .htaccess file:

RewriteEngine On

After this step, i have absolutely no idea whats !-d nor {REQUEST_FILENAME} nor ^(.*) and all that programming text. Is there a documentation that i can refer to?

Or can anyone provide me a simple explanation on how to configure the .htaccess file to understand that if i want to go to

www.example.com/pageone.html

, all i need to type into the URL is

www.example.com/pageone/

and PHP files, etc as well?

like image 864
Kyle Yeo Avatar asked Dec 17 '22 00:12

Kyle Yeo


1 Answers

First of all, there's the Official Documentation. To solve your specific problem, I would go about this way:

RewriteEngine on #Turn on rewrite

RewriteCond %{REQUEST_FILENAME} !-f #If requested is not a filename...
RewriteCond %{REQUEST_FILENAME} !-d #And not a directory
RewriteRule ^([^/]+)/?$ /$1.html [L] #Preform this redirect

The RewriteConds only apply to the next following rule. If you were to have multiple rules, you'd need to write the conditions for each one.

Now, the Apache server matches the requested path (everything after www.example.com/), to see if it matches any of the rules you've specified. In which case, there is only one:

^([^/]+)$

This regular expression matches any number of characters, which are not slash /, followed by an optional trailing slash. If the match was found, it will rewrite the request to the second parameter: /$1.html, $1 means "Whatever was matched between the brackets", which in our case is all of the non-slash characters.

The [L] flag, tells the rewriting engine to stop looking for rules if this rule was matched.

So to conclude, www.example.com/whatever/ will be rewritten sliently at the server to www.example.com/whatever.html

like image 92
Madara's Ghost Avatar answered Jan 02 '23 18:01

Madara's Ghost