My url is http://localhost/store/product-detail.php?p=prod%name%test i want it to look like this http://localhost/store/prod-name-test or something like this as other stores do http://localhost/store/p/prod-name-test

I tried so many codes on .htaccess none of them worked. This is my current code

# mod_rewrite starts here 
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}\.php -f

RewriteRule \//product-detail.php\s(.*) http://localhost/store/p/?p=Dress$1 [R=301,L]

#RewriteRule ^users/(\d+)*$ ./product-detail.php?p=$1
#RewriteRule ^?([a-zA-Z0-9=_-]+)$ product-detail.php?$1 [NC,L] 
#Options +FollowSymLinks
#RewriteRule ^/?$ /product-detail.php [QSA,L]

I tried also window.history.pushState("", "", "/p/<?php echo $prod_name; ?>");. It doesn't work.

The most important thing is that the link should respect the SEO. I should also be able to use the request method ?p= even if its hidden.

  • 1
    .htaccess can't modify the links in your HTML pages. I'm not sure if that is what you mean by "link should respect the SEO", but if so, you need to find another solution for that part. Dec 20 '19 at 22:46
  • "?p=prod%name%test" - You've used unencoded % in your actual URL - is this intentional? (So this would also require conversion to - in your "desired" URL format?)
    – MrWhite
    Dec 21 '19 at 0:38

You are on the right path by using url rewriting but your rewrite rules can be simplified.

.htaccess File

<IfModule mod_rewrite.c>
    <IfModule mod_negotiation.c>
        Options -MultiViews -Indexes

    RewriteEngine On

    # Handle Authorization Header
    RewriteCond %{HTTP:Authorization} .
    RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]

    # Redirect Trailing Slashes If Not A Folder...
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_URI} (.+)/$
    RewriteRule ^ %1 [L,R=301]

    # Handle Front Controller...
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^ index.php [L]

What this .htaccess file will do is redirect all browser requests which don't match an actual directory or file in your web application to the index.php file. From there you can then decode the URL to handle is however you wish.

In this way by using a very simple rewrite rule you can use URL's such as domain.com/store/category-name/product-name and return the appropriate data.

A good starting point for a lot of this would be to take a look at any number of PHP application frameworks which include request routing as part of the underlying package.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.