Christos Hayward
Christos Hayward

Reputation: 5993

How can I canonicalize URLs in my .htaccess?

I have a Wordpress installation on a LAMP stack, and if I have a post at http://example.com/abc/ , I would like URLs like http://example.com/abc/def.html to be redirected to http://example.com/abc/ . (Note that the slot here occupied by "def" should be without any slashes; this means among other things that things under http://example.com/wp-content/ should be unhindered.)

The rewrite I tried is:

RewriteRule ^(/[^/]+/)[^/]+\.html$ $1 [R=301,L]

As far as I can tell, that says, "Take the first two slashes and everything between them, matching on no more slashes and ending in .html, and redirect to the first captured group." However, with that in place, I can access http://example.com/abc/ , but I get a 404 on attempted access to http://example.com/abc/def.html .

What should I be doing to put the desired redirect behavior in place?

Thanks,

Upvotes: 1

Views: 31

Answers (1)

anubhava
anubhava

Reputation: 785256

Try this rule:

RewriteRule ^/?([^/]+/)[^/.]+\.html$ /$1 [NC,R=301,L]

make leading slash optional as .htaccess doesn't have it and tweak part after first slash. Make sure this is your very first rule.

Upvotes: 1

Related Questions