1

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?

5

Something like

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

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

  • Is there a way to do this such that it only redirects if the new url actually exists? – Travis Northcutt 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! – Travis Northcutt 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... – Travis Northcutt Nov 16 '09 at 21:10

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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