apache.htaccessmod-rewriteurl-rewritingfriendly-url

How to rewrite below urls patterns to specific php files using htaccess?


I have two dynamic urls which I want to redirect on different php's. Problem is that both urls are dynamic. So it is difficult for me to catch patterns and redirect them.

I search on google and found many examples but all examples url containing some pattern to catch.

Below is the my sample urls along with respective php's.

https://www.example.com/my-dynamic-category/my-dynamic-url-id/

should redirect to

https://www.example.com/detail.php?p=my-dynamic-url-id

As well:

https://www.example.com/my-dynamic-category/

should redirect to

https://www.example.com/category.php?p=my-dynamic-category

Can anyone please help me?

I tried with below rule for my detail.php redirection,

RewriteRule ^\/detail/?$  /detail.php?url=$1$2 [R=301,L]

but problem with this rule is that it will work only if url contains word detail


Solution

  • With your shown attempts/rules please try following rules in your .htaccess file. Please make sure to clear your browser cache before testing your URLs.

    RewriteEngine ON
    ##Rules for handling https://www.example.com/my-dynamic-category/ 
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^([^/]*)/?$ category.php?p=$1 [L]
    
    ##Rules for handling https://www.example.com/my-dynamic-category/my-dynamic-url-id/
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^([^/]*)/(.*)/?$ detail.php?p=$2 [L]