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 Adding A Trailing Slash

.htaccess

In an earlier code challenge, we wrote a rewrite rule so that the web page http://localhost/flavors/ executed the code at all_flavors.php. Unfortunately, this only works if the web address includes the trailing slash. If someone visits http://localhost/flavors, they will see a 404: Page Not Found error. We'll need another rewrite rule to redirect from /flavors to /flavors/. Add a new line to the htaccess file below to accomplish this.

RewriteEngine  On   
RewriteRule ^flavors/$ /all_flavors.php

what should i do after this?

2 Answers

RewriteRule ^flavors$ /flavors/ [R=301]

The key to this rewrite is the "$" which matches the end of the string. Remember though, this matches a position, not a character.

Outside of this challenge, I would do this

RewriteRule ^flavors/?$ /flavors/ [R=301]

The ? means optional in regular expression speak.

thank you for your time janson, i test it, but it doesn't work, i don't know why!

This is just for anyone who views this for help on the challenge. I know that this one can be a little difficult..

RewriteEngine  On   
RewriteRule ^flavors/$ /all_flavors.php
RewriteRule ^(flavors)$ /$1/ [R=301]
Chris Collier
Chris Collier
17,774 Points

Hi thanks for this. I was having a lot of trouble on this challenge and this is the only way I could get past it. I never would have figured this out. What I was doing different is:

RewriteRule ^(/flavors)$ /$1/ [R=301]

The only difference with mine is that I had the leading forward slash in my first part of the rewrite. I don't understand why it works when we match to flavors without the first forward slash and then serve back flavors with a forward slash afterwards AND before. Wouldn't that cause a double-forward slash at that part of the address before the word "flavors"?