Reputation: 87
As we simplified the URLs of our profiles from example.com/category/profile/
to example.com/profile
, et cetera (including the automatic removal of all trailing slashes -- see Vanity URLs without trailing slashes), we now need to redirect all inbound links bound for the old URLs. We found a way to do this with the following code (which also excludes the files and directories we needed to keep).
RewriteCond %{REQUEST_URI} !^/category/index [NC] #Excludes /category/index.html from redirect
RewriteCond %{REQUEST_URI} !^/category/images [NC] #Excludes /category/images/ from redirect
RewriteCond %{REQUEST_URI} !^/category/menu [NC] #Excludes /category/menu/ from redirect
RewriteRule ^category/(.+[^/]) /$1 [R=301,NC,L]
But this only works if we keep all the original directories that contain our individual profiles; if we delete these directories, the redirect no longer works. We tried the below, but that didn't help.
RewriteCond %{REQUEST_URI} !^/category/index [NC]
RewriteCond %{REQUEST_URI} !^/category/images [NC]
RewriteCond %{REQUEST_URI} !^/category/menu [NC]
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^category/(.+[^/]) /$1 [R=301,NC,L]
We were looking into an alternative (and much simpler) way to do this using RedirectMatch (code below), but we did not find a way to exclude the directories we need to keep and this also did not remove any trailing slashes from the original, inbound links.
RedirectMatch 301 ^/category/(.*)$ /$1
Upvotes: 1
Views: 45
Reputation: 41249
Try :
RedirectMatch ^/category/((?!index|images|menu|foo|bar)[^/]+)/?$ /$1
Upvotes: 1