简体   繁体   中英

HTACCESS : Redirect (301) thousands of Url's containing directories to simple url's

I need to convert with.HTACCESS method tons of URL's allready produced (and already indexed ...) by Wordpress for articles containing folders/subfolders to simples URL's without any folder/subfolder name .

Example:
FROM https://www.website.com/Animals/Cats/mycat.html TO https://www.website.com/mycat.html
FROM https://www.website.com/Animals/Dogs/mydog.html TO https://www.website.com/mydog.html
FROM https://www.website.com/Countries/France/bordeaux.html TO https://www.website.com/bordeaux.html
etc...

I already changed permalinks options in Wordpress config. So, now URL's produced are in the good format (Ex: https://www.website.com/bordeaux.html ) without any folder name.

My problem is to redirect all OLD Url's to this new format to prevent 404 and preserve the rank.

If tryed to add in my.htacess this line:
RewriteRule ^/(.*)\.html$ /$1 [R=301,L,NC]
I egally tryed RedirectMatch 301 (.*)\.html$ method and it's the same. I'm going crazy with this.
What am i doing wrong and could you help me?

Thanks

Just match the last part of the url and pass it to the redirect:

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

It will match any number of directories like:

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

The URL-path matched by the RewriteRule pattern never starts with a slash. But you can use this to only match the last path-segment when there are more "folders". And the target URL also needs to end in .html (as per your examples).

So, this can be written in a single directive:

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

This handles any level of nested "folders". But does not match /foo.html (the target URL) in the document root (due to the slash prefix on the regex), so no redirect-loop.

(No need for any preceding conditions .)

Here the $1 backrefence includes the .html suffix.

Redirect the old URLs to the new ones without the folder names. You can use the following code to redirect URLs that contain.html:

RewriteEngine On
RewriteRule ^([^/]+)/([^/]+)/([^/]+)/([^/]+)/([^/]+).html$ /$5.html [L,R=301]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM