Firstly, you are operating out of a sub-directory (MyWeb
), which means you need to set a RewriteBase
. Also, you need to ensure that your .htaccess
file is placed inside that sub-directory, and not in the localhost document root.
So, below RewriteEngine on
, insert the folloeing line:
RewriteBase /MyWeb/
Next, you stated that you want to convert project.php?id={id}
to project/id/{id}
, but your code omits the /id/
segment. I also noticed that you have two rules, and that the second one contradicts your question, so I am only going to show you the change you need to make for the first rule, until such time as you clarify what the second rule is for.
To make the project URI work, change the very first rule to:
RewriteRule ^project/id/([0-9]+)/?$ project.php?id=$1 [QSA,L]
This will match the URI you want, with an optional trailing slash. I've also added the QSA
flag which appends any extra query string parameters to the rewitten URI, as well as the L
flag which stops processing if the rule is matched.
Next, to omit the .php
or .html
from your URIs, change the last three lines to the following:
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule ^([^\.]+)$ $1.php [L]
RewriteCond %{REQUEST_FILENAME}.html -f
RewriteRule ^([^\.]+)$ $1.html [L]
When you make a request to localhost/MyWeb/index
, Apache will check to see if localhost/MyWeb/index.php
or localhost/MyWeb/index.html
exist, and will then serve whichever one it finds first.
If you have both the PHP and HTML files, then the PHP one will be served, and not the HTML one. If you prefer to serve HTML files, then swap the two blocks around.
Unfortunately, I don't know of a good way to force a trailing slash for these, specifically because of the condition that checks for their existence. In other words, it won't work if you request sub2/
, with the trailins slash because it would need to check if sub2/.php
exists, which it does not.
Update: For added benefit, place these two blocks just below the new RewriteBase
you set earlier to redirect the old URIs to the new ones whilst allowing the rewrites to the new URIs to still work:
RewriteCond %{THE_REQUEST} \/project\.php\?id=([0-9]+) [NC]
RewriteRule ^ project/id/%1/ [R=302,L,QSD]
RewriteCond %{THE_REQUEST} \/MyWeb/(.+)\.(php|html)
RewriteCond %{REQUEST_FILENAME} -f
RewriteRule ^ %1 [R=302,L]
For reference, here's the complete file: http://hastebin.com/gacapesoqe.rb