.htaccess - mod rewrite for URLs

smoochy boys on tour

ChronicleGM

Dedicated Member
Dedicated Member
Oct 24, 2004
232
1
65
Evening all,

I am looking for a little assistance with mod rewrite for apache.

I am building my own eCommerce platform and I want to rewrite my dynamic URLs to friendly URLs.

An example, I want:

I want: http://www.peakwebdesigns.co.uk/ecommerce/product_page?id=3
to be http://www.peakwebdesigns.co.uk/ecommerce/product/3

This is my current .htaccess with the rewrite rule:


RewriteEngine On


RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^([^\.]+)$ $1.php [NC,L]


RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^([^\.]+)$ $1.html [NC,L]


RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^product/([^\s\/]+)/?$ product_page.php?id=$1 [END]

Can anyone help me?

Thanks.
Stan.
 

Risen28

LOMCN Rookie
Aug 20, 2017
12
1
14
south africa
Hello Are you on wordpress by any chance? If so you can change it in the settings on admin panel also i would suggest downloading seo tool for rel canonical tags and meta description tags .

[FONT=Helvetica, Arial, sans-serif] Mod rewrite won't change the hyperlinks you output. Only how those URLs are handled.[/FONT]
[FONT=Helvetica, Arial, sans-serif]
The cosing is in context to another site but it makes sense to me , here is the thread

[/FONT]<https://www.sitepoint.com/community/t/using-mod-rewrite-to-make-dynamic-url-friendly/81500/7>[FONT=Helvetica, Arial, sans-serif]

[/FONT]/**
* Create URL safe title
* @param string $title
* @return string
*/

function title_slug($title) {
$slug = strtolower(trim($title));
$slug = preg_replace('/ +/', '-', $slug);
$slug = preg_replace('/[^a-z0-9\\.\\,\\_\\-]/', '', $slug);

return $slug;
}

Pass in your full text titles to that function. It will convert spaces to dashes, and then remove everything except for alpha numeric characters and . , _ -
This will be much tidier than doing the filtering inline.
I'd go a step further and write a function to return the HTML hyperlink from the link data. By doing this you can change the format of the link at any time, and the flow of your code will be easier to understand.
/**
* Build the href value for news links
* @param string $id
* @param string $title full unfiltered HTML title
* @return string
*/

function news_link($id, $title) {
$slug = title_slug($title);
return "news/$slug/$id/";
}

To use:
$href = news_link($row_BusinessInsuranceNews['newsArticleID'], $row_BusinessInsuranceNews['htmlTitle']);
echo "<a href='$href'>more</a>";
 

ChronicleGM

Dedicated Member
Dedicated Member
Oct 24, 2004
232
1
65
This is brilliant, thank you!

I'll give it a try, however I did get it working using the following:

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^ecommerce/product/(.*)$ ./ecommerce/product?id=$1 [L,NC]


RewriteRule ^ecommerce/category/(.*)$ ./ecommerce/category_page?category_name=$1 [L,NC]