Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

PHP Enhancing a Simple PHP Application Cleaning URLs with Rewrite Rules Introducing Rewrite Rules

Steven Burgess
PLUS
Steven Burgess
Courses Plus Student 5,624 Points

Rewrite Rule will not work

I'm using A Small Orange to host the site, but I can't get the Rewrite Rule to work at all like in the video... I've tried everything and looked at a lot of resources, but I can't get it to work at all. I know the Rewrite is enable because this code does something

RewriteRule ^(.*)/$ /$1.php [L]

But I can't get this to work for the life of me.

RewriteEngine On RewriteRule ^shirts/$ shirts/shirts.php

1 Answer

Ron McCranie
Ron McCranie
7,837 Points

I think what you're looking for is this:

RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{DOCUMENT_ROOT}/$1.php -f
RewriteRule ^(.*?)/?$ $1.php [L]

The rewrite will make sure the 2 conditions are met before using the rule. So first it looks to see if the REQUEST_FILENAME is not a directory (!-d) then moves to the next condition. The second condition checks to see if the the DOCUMENT_ROOT (everything before the last slash) plus the filename with a php extension exists, if that's true it moves on to the rule. The rule states that we want to take everything before the last slash and keep it the same, then take the text after the last slash and add a .php extension.

Steven Burgess
Steven Burgess
Courses Plus Student 5,624 Points

This is my first time using the forum function or I would have added some more background.

What I'm trying to do is have someone who goes to site/projects/store/shirts to be directed to site/projects/store/shirts/shirts.php

However in the url bar I want it to still show site/projects/store/shirts

Also, when I add that code to .htaccess it doesn't appear to do anything. Does it matter which director .htaccess is in?

RewriteEngine On
RewriteRule ^shirts/$ /shirts/shirts.php
RewriteRule ^shirts/([0-9]+)/$ /shirts/shirt.php?id=$1
RewriteRule ^receipt.php$ /receipt/ [R=301]
RewriteRule ^contact.php$ /contact/ [R=301]
RewriteRule ^shirts.php$ /shirts/ [R=301]
RewriteRule ^(shirts/[0-9]+)$ /$1/ [R=301]
RewriteCond %{QUERY_STRING} ^id=([0-9]+)$
RewriteRule ^shirt.php$ /shirts/%1/? [R=301]

This is the code the video tells me I should have, but it doesn't do anything