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

Leigh Maher
Leigh Maher
21,830 Points

Rewrite rule only worked when I included the sub-folder name?

When I followed this instructions initially, the rewrite rule did not work for me. My project is set up in a sub folder of the local host so I decided to include that in the path like this:

RewriteRule ^shirts/$ /mysubfolder/shirts/shirts.php

This worked for me but I'm wondering why would I need to include this in the rewrite rule as the .htaccess in located in this subfolder?

Does this mean that no matter where you put the .htaccess file it will always look to the root of the server?

Thanks.

3 Answers

Sean T. Unwin
Sean T. Unwin
28,690 Points

A RewriteRule by default is based off the root of the server (absolute path) so that is why you needed to use, RewriteRule ^shirts/$ /mysubfolder/shirts/shirts.php.

There is a directive called " RewriteBase" which allows you to use a relative path in your RewriteRule's. The directive (RewriteBase) is placed above any RewriteRule's that are to be associated with this directive.

Below is an example which is copied from my .htaccess for this project:

RewriteEngine On
RewriteBase /treehouse/php/shirts4mike2
RewriteRule ^shirts/$ shirts/shirts.php
Leigh Maher
Leigh Maher
21,830 Points

Thanks Sean. I subsequently found that solution, and it works nicely. Thanks for your reply.

Michael Tigue
Michael Tigue
4,799 Points

I had to put the .htaccess file in the root folder of both my web server and my local machine. I have the entire project in a folder called /shirts. For me, putting the .htaccess in the / shirts folder did not work. I had to put it the parent folder above /shirts, which is the root folder of my web server.

Then, inside the .htaccess file, I had to include the path to the /shirts folder. To avoid confusion, I made the shirts folder referred to in the lesson called shirts2. Here is my .htaccess file code that works.

RewriteEngine On

RewriteRule ^shirts/shirts2/$ /shirts/shirts2/shirts.php

Zeljko Porobija
Zeljko Porobija
11,491 Points

Yep, Sean is right. So, firstly we need RewriteBase (in my case /projects/WebShop and only then there goes RewriteRule (no need for anything but ^shirts/$ shirts/shirts.php)