Is there any way to redirect to a clean url when old url is requested?

Viewed 107

I want to change the URLs on my website from page.php?id=1&name=john to page/1/john using htaccess RewriteRule.

This is what I have currently but it is not working as expected:

RewriteRule ^page/([0-9]+)/([a-zA-Z\s-]+) page.php?id=$1&name=$2

Is it possible to make this change in htaccess rules or should I change every link to <a href='page.php/1/john'>Page</a> which is tiresome since I have got many links in every page. Help is appreciated. Thanks.

2 Answers

1st solution: To get from query string URL to user friendly url try following, as per OP's request.

Options -MultiViews
RewriteEngine On
RewriteBase /rootfolder/
RewriteCond %{QUERY_STRING} ^id=(\d+)&name=([\w-]+)/?$ [NC]
RewriteRule ^([^.]*)\..*$ /$1/%1/%2/ [QSD,R=302,NC,L]


2nd solution: As far as I get from OP's question, could you please try following. Considering as per thumb rule users will be given friendly URL like eg--> http://localhost:80/page/1/john and it will point in pointed to http://localhost/page.php?id=1&name=john in backend.

Options -MultiViews
RewriteEngine On
RewriteBase /rootfolder/
RewriteCond %{QUERY_STRING} ^$
RewriteRule ^([^/]*)/([^/]*)/(.*)/?$ /$1.php?id=$2&name=$3 [NC,L]

You may use these 2 rules in site root .htaccess:

Options -MultiViews
RewriteEngine On
RewriteBase /rootfolder/

# external redirect from actual URL to pretty one
RewriteCond %{THE_REQUEST} /page\.php\?id=(\d+)&name=([^\s&]+)\s [NC]
RewriteRule ^ page/%1/%2? [R=302,L,NE]

# internal forward from pretty URL to actual one
RewriteRule ^page/(\d+)/([^/]+)/?$ page.php?id=$1&name=$2 [L,QSA,NC]
Related