Gags
Gags

Reputation: 3839

Redirect 301 Dynamic URLs htaccess

I Have a rule in my htaccess as below

RewriteRule ^([^/.]+)/([^/.]+)/([^/.]+)/?$ /detail_new?
location=$1&id=$2&name=$3 [L,QSA]

And it is working pretty fine as when i type URL as http://example.com/location/id/name

But when i type http://example.com/detail_new.php?location=Panchkula&id=123&name=ABC then also page opens up.

But here i want that http://example.com/detail_new.php?location=XYZ&id=123&name=ABC should always be redirected to http://example.com/location/id/name

I Handeled in PHP as below

$url = 'http://' . $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI'];
 if ((false !== strpos($url,'detail_new')) {
   $rebuilt_url = "http://example.com/location/id/name";
   header ("HTTP/1.1 301 Moved Permanently");
   header("Location: {$rebuilt_url}") ;  // redirect to this url
}

How can i do same in htaccess please.

Upvotes: 2

Views: 99

Answers (1)

anubhava
anubhava

Reputation: 786289

You can add this rule to redirect actual URL to pretty one before your earlier rule:

RewriteCond %{THE_REQUEST} \s/+detail_new\?location=([^\s&]+)&id=([^\s&]+)&name=([^\s&]+) [NC]
RewriteRule ^ /%1/%2/%3? [R=302,L,NE]

RewriteRule ^([^/.]+)/([^/.]+)/([^/.]+)/?$ /detail_new?location=$1&id=$2&name=$3 [L,QSA]

Upvotes: 1

Related Questions