Search code examples
php.htaccessmod-rewriteurl-rewritingfriendly-url

Rewrite url not working with hyphen "-" using .htaccess with php


I'm trying to make my url user-friendly by using .htaccess rewrite.

from url - http://localhost/Web/new_products.php?cat_id=1&cat_title=new-rocket

to url - http://localhost/Web/new-rocket-1.php

in my new_products.php

$get_cat = "select * from new_products_cat";
$run_cat = mysqli_query($con, $get_cat);
while($row_cat = mysqli_fetch_array($run_cat)){
                    
$cat_id = $row_cat['cat_id'];
$cat_title = $row_cat['cat_title'];
$hyphen_cat_title = str_replace(' ', '-', $cat_title);
                    
echo "
<a href='new_products.php?cat_id=$cat_id&cat_title=$hyphen_cat_title'>
......
......
......

in my .htaccess

<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteCond %{THE_REQUEST} /Web/new_products.php\?cat_id=([^&\s]+)&cat_title=([^&\s]+) [NC]  
    RewriteRule ^ /Web/%2-%1\.php? [NC,R,L,NE]
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^([^-]+)-([^.]+)\.php$ /Web/new_products.php?cat_id=$2&cat_title=$1 [QSA,L,NC]
</IfModule>

Question 1

My code working only if i use "underscore". $hyphen_cat_title = str_replace(' ', '_', $cat_title);

But not working if i use "hyphen", its keep redirecting to http://localhost/Web/new_products.php

Question 2

Can i replace "space" to "hyphen" using rewrite in .htaccess? without using php str_replace


Solution

  • For my Question 1

    The problem was [^-] “every character but a hyphen”. Thanks to @CBroe

    Below code fixed my problem.

    RewriteRule ^([^.]+)-([^.]+)\.php$ /Web/new_products.php?cat_id=$2&cat_title=$1 [QSA,L,NC]