Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating dynamic URLs in htaccess

Tags:

php

.htaccess

I'm trying to write an .htaccess file that will make my URLs more attractive to search engines. I know basically how to do this, but I'm wondering how I could do this dynamically.

My URL generally looks like:

view.php?mode=prod&id=1234

What I'd like to do is take the id from the url, do a database query, then put the title returned from the DB into the url. something like:

/products/This-is-the-product-title

I know that some people have accomplished this with phpbb forum URLs and topics, and i've tried to track the code down to where it replaces the actual URL with the new title string URL, but no luck.

I know I can rewrite the URL with just the id like:

RewriteRule ^view\.php?mode=prod&id=([0-9]+) /products/$1/

Is there a way in PHP to overwrite the URL displayed?

like image 670
chaoskreator Avatar asked Feb 24 '23 08:02

chaoskreator


1 Answers

At the moment you're wondering how to convert your ugly URL (e.g. /view.php?mode=prod&id=1234) into a pretty URL (e.g. /products/product-title). Start looking at this the other way around.

What you want is someone typing /products/product-title to actually take them to the page that can be accessed by /view.php?mode=prod&id=1234.

i.e. your rule could be as follows:

RewriteRule ^products/([A-Za-z0-9-])/?$ /view.php?mode=prod&title=$1

Then in view.php do a lookup based on the title to find the id. Then carry on as normal.

like image 178
Matthew Avatar answered Mar 05 '23 00:03

Matthew