Search code examples
.htaccessmod-rewrite

htaccess dynamic url redirect


I have the following URL

https://example.com/expert-profile?id=john-doe&locale=en

I want it to be redirected to

https://example.com/expert/john-doe

I tried the following

RewriteCond %{QUERY_STRING} ^(([^&]*&)*)id=([^&]+)&?(.*)?$
RewriteRule ^expert-profile$ https://example.com/expert/%3?%1%4 [L,R=301]

And a couple of other solutions, nothing is working here. Can someone help me to go in the right direction?

Update:

This is my current .htaccess file

<IfModule mod_rewrite.c>

  RewriteEngine On
  RewriteBase /
  RewriteRule ^index\.html$ - [L]
  RewriteCond %{REQUEST_FILENAME} !-f
  RewriteCond %{REQUEST_FILENAME} !-d
  RewriteCond %{REQUEST_FILENAME} !-l
  RewriteRule . /index.html [L]

</IfModule>

Redirect 301 "/en/download-app" "/download-app"

Solution

  • Please keep your htaccess file in your root and have it in following way. Please clear your browser cache before testing your URLs.

    RewriteEngine ON
    RewriteCond %{QUERY_STRING} ^id=([^&]*)&locale=(.*)$ [NC]
    RewriteRule ^([^-]*)-.*/?$ $1/%1-%2 [R=301,L]
    


    OR in case you don't have Rules to handle non-existing files/directories then use following Rules set. Please make sure either use above OR following Rules set one at a time only.

    RewriteEngine ON
    RewriteBase /
    RewriteRule ^index\.html$ - [L]
    
    RewriteCond %{QUERY_STRING} ^id=([^&]*)&locale=(.*)$ [NC]
    RewriteRule ^([^-]*)-.*/?$ $1/%1-%2 [R=301,L]
    
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^(?:expert)/([^-]*)-(.*)$ $1-profile?id=$1&locale=$2 [NC,L]
    
    
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME} !-l
    RewriteRule ^ /index.html [L]