I'm trying to figure out how to write an .htaccess rule that will do the following:

/example1/removethis/item

becomes

/example1/item

and

example2/removethis/item2

becomes

example2/item2

etc. I should note that 'removethis' is always the same, but I want it to work for anything in the place of 'example1' and anything in the place of 'item', if that makes sense. I'd also like it to be a 301 (permanent) redirect. Thoughts?

link|improve this question
feedback

1 Answer

up vote 5 down vote accepted

Something like

RewriteRule ^(.*)/removethis/(.*)$ $1/$2

Should do the trick. Setting the redirect code and whatnot left as an exercise for the reader.

link|improve this answer
Is there a way to do this such that it only redirects if the new url actually exists? – tnorthcutt Nov 16 '09 at 20:02
That depends on what you mean by "exists". – womble Nov 16 '09 at 20:34
I mean "going to that url will not result in a 404". What I'm trying to do is change over the directory structure of some pages to example/item (from example/removethis/item), but I don't have the time/inclination to change them all at once, so it would be nice if it only redirects if example/item exists. Regardless, your answer works perfectly! – tnorthcutt Nov 16 '09 at 20:42
No, you can't test whether the destination will result in a 404 and then not apply the rewrite, but I can't imagine that the extra redirect to a 404 would be that much worse over and above a direct 404. – womble Nov 16 '09 at 20:44
Forgive me - I don't really understand what you mean by that last part... – tnorthcutt Nov 16 '09 at 21:10
feedback

Your Answer

 
or
required, but never shown

Not the answer you're looking for? Browse other questions tagged or ask your own question.