Rob S
Rob S

Reputation: 27

Htaccess remove string from URL behind last slash

Looking for solution how to remove anything behind URL last slash.

example output URL:

http://example.com/pictures/123/category-name/

problems to avoid for this URL:

http://example.com/pictures/123/category-name/blah.html
http://example.com/pictures/123/category-name/blah/blah.html
http://example.com/pictures/123/category-name/blah/blah/blah.html
http://example.com/pictures/123/category-name/blah/
http://example.com/pictures/123/category-name/blah

So far i have this:

RewriteRule ^([A-Za-z0-9-]+)/([0-9]+)/category-name/$ $1/$2/category-name/ [R]
RewriteRule ([A-Za-z0-9-]+)/([0-9]+)/category-name/(.*)$ category.php?VarA=$1&VarB=$2

it works for output URL and the URL with anything behind pattern. Problem is that it doesn't rewrite (redirect) to output URL if anything is behind last slash.

Upvotes: 0

Views: 152

Answers (1)

Ultimater
Ultimater

Reputation: 4738

I'd personally use logic which is straight-forward like this:

#redirect to canonical url if no ending slash
RewriteRule ^([A-Za-z0-9-]+)/([0-9]+)/category-name$ $1/$2/category-name/ [R,L]
#redirect to canonical url if anything behind slash
RewriteRule ^([A-Za-z0-9-]+)/([0-9]+)/category-name/(.+)$ $1/$2/category-name/ [R,L]
#rewrite to PHP file if visiting the canonical url
RewriteRule ^([A-Za-z0-9-]+)/([0-9]+)/category-name/$ category.php?VarA=$1&VarB=$2 [L]

Upvotes: 1

Related Questions