If I have a dynamic page, where it takes in an id parameter like example.com/posts.php?id=2, how do I make a RewriteRule in htaccess so that the url shows the title of the post rather than its id, so for example posts.php?id=2 shows a post with a title of “PHP is cool”, I want the url to be rewritten like example.com/2/php-is-cool or something like that? Would that be possible if the title value is stored in a MySQL database?
Additional Info:
This is how my htaccess looks like:
RewriteEngine On
RewriteCond %{HTTP_HOST} ^mydomain\.com$
RewriteRule (.*) http://www.mydomain.com/$1 [R=301,L]
ErrorDocument 404 /index.php
ErrorDocument 403 /index.php
php_value post_max_size 20M
Basically, I have a MySQL database which stores blog posts in a table called posts. The posts table has an id attribute (which is the auto-increment primary key), a title attribute, and a content attribute. When I access mydomain.com/posts.php?id=X, it will show my post with an id of ‘X’ from the database on the webpage. I just want to be able to re-write the URL such that it shows the title of the page. I’m doing this primarily for SEO, not aesthetics. Is this possible using htaccess, or would I have to approach this differently?
Rewrite rules apply to the way the URL is handled on your backend (apache). Using mod_rewrite to rewrite those URLs will not affect what the user is seeing in their browser’s URL bar unless you redirect the user to a new URL (using a 302 redirect, for example), which would cause the browser to reload the page.
You can achieve what you’re asking for using the HTML5 pushstate feature (with a fallback to URL hashes if pushstate is not supported in that browser).
Take a look at this URL for more details:
http://badassjs.com/post/840846392/location-hash-is-dead-long-live-html5-pushstate
Also, you could use BackboneJS and its Router feature to handle your page and URL handling logic in the browser.
http://backbonejs.org/#Router
This is a very application specific kind of solution and this answer cannot go into more details without knowing your exact configuration, application logic, etc.