Hopefully some of you .htaccess gurus can help me out with this one. I have never spent any time messing around with .htaccess before, so I'm a bit lost.
Basically I want to take a link such as example.com/index.php?id=3 and convert it to http://example.com/pagename/
I can easily change it so that the link converts to http://example.com/directory/3 or something along those lines, but I don't really understand how people accomplish the change I'm looking for. I know that Wordpress does something similar with their urls, but how are they accessing the post name information?
Wordpress does it by rewriting everything that doesn't resolve as a file or directory to
index.php
, it looks like this:And index.php reads the requested URI and figures out what to do with it. At the same time, wordpress knows that these URLs are being rewritten so it renders pages with clean SEO friendly URLs like
http://example.com/pagename/
.For your example, mod_rewrite itself isn't going to be able to know that id=3 equates to pagename unless you hardcode a bunch of individual RewriteRules. What you can do it make index.php accept the pagename so your rule will look something like this:
Now it's up to generating the clean SEO friendly URLs in your content. In Content Management Systems, the pages themselves are usually stored in a database under an ID of some kind. Say a page "Test Page" with an ID in the database as "5", created on October 10th, 2011. When the CMS needs to generate a link, it looks in the database and constructs the link as
/2011/10/Test_Page
.So when you go to, say, the front page, index.php generates links to all its pages and for "Test Page", the link says
/2011/10/Test_Page
, and when someone clicks on that link, apache uses a rule likeRewriteRule ^([0-9]+)/([0-9]+)/(.+)$ /index.php?year=$1&month=$2&title=$3 [L]
to rewrite the URL to/index.php?year=2011&month=10&title=Test_Page
. The index.php script looks in the database for the correct page and returns it to the browser. This is going to be different for each CMS. Essentially, .htaccess won't know anything that's stored in your database, but it can rewrite links so that required information (like "id" or "page") gets passed to a script. It's up to the script to both decide what page to return and to generate the clean SEO-friendly links on that page.