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 Rewrite Rules with Query Strings

Zach Saul
Zach Saul
11,156 Points

Rewrite messing up

When I go to localhost/shirt.php?id=108, it redirects to /localhost/shirts instead of localhost/shirts/108. Why? Below is my rewrite code

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]

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

Zach Saul
Zach Saul
11,156 Points

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]

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

2 Answers

Shivam Sadachar
Shivam Sadachar
8,109 Points

I used your code in my .htaccess file and everything seemed fine. Just make sure each RewriteRule is on a seperate line in your text editor. Otherwise, your code worked great for me.

Do you still have any problems?

Zach Saul
Zach Saul
11,156 Points

Yeah so I test it out some more and I found that problem has to be with the second line:

RewriteRule ^shirts/$ /shirts/shirts.php

For some reason, whenever I change the test within the ^$, it works fine. For example

RewriteRule ^shirsdafdsfasts/$ /shirts/shirts.php <-This works.

This leads me to believe it has nothing to do with the .htaccess file

Zach Saul
Zach Saul
11,156 Points

To recap, whenever I use: RewriteRule ^shirts/$ /shirts/shirts.php, it redirects me to localhost/shirts/shirts.php when it should keep me at localhost/shirts/.