How to ignore URL at the end of URL

Viewed 85

I have a URL

original: https://www.example.com/video/12345/name-of-the-video/

Sometimes users or web crawlers write the URL differently:

https://www.example.com/video/12345/name-of-the-video/65485/

https://www.example.com/video/12345/

https://www.example.com/12345/

I want all 3 URLs to redirect (forward) to the original:

https://www.example.com/video/12345/name-of-the-video/

My current htaccess rule is:

RewriteRule ^video/([0-9]+)/([^/]+)/$      view_video.php?id=$1&dir=$2 [L,QSA]
RewriteRule ^video/([0-9]+)/$              view_video.php?id=$1&dir=fake [L,QSA]
1 Answers

Could you please try following, written based on your shown samples. Please make sure you clear your browser cache before testing your URLs.

RewriteEngine ON
##To rewrite URL https://www.example.com/12345/
RewriteRule ^([0-9]+)/?$ view_video.php?id=$1&dir=fake [NC,L]

##To rewrite URL https://www.example.com/video/12345/
RewriteRule ^video/([0-9]+)/?$ view_video.php?id=$1&dir=fake [NC,L]

##To rewrite URL https://www.example.com/video/12345/name-of-the-video/65485/
RewriteRule ^video/([0-9]+)/([\w-]+)/[0-9]+/?$ view_video.php?id=$1&dir=$2 [R=301,NC]
RewriteCond %{REQUEST_URI} ^/view_video\.php [NC]
RewriteCond %{QUERY_STRING} id=([^&]*)&dir=(.*) [NC]
RewriteRule ^(.*) video/%1/%2 [R=301,L]

##To rewrite URL https://www.example.com/video/12345/name-of-the-video/
RewriteRule ^video/([0-9]+)/([\w-]+)/?$ view_video.php?id=$1&dir=$2 [NC,L]
Related