The following solution will only work if your products have only 1 category.
This code will work deleting at admin product grid and admin product view.
This code will make a redirect to the category the product is in. Except if that category has no products after deleting, it will use the parent category of the product category instead. This creates a problem because many of the rewrites will still link to a category without products.
If this is not a problem for you use the following solution.
In ./app/code/local/INPUTANAME/RewriteAfterDelete/etc/config.xml put
<?xml version="1.0" encoding="UTF-8"?>
<config>
<modules>
<INPUTANAME_RewriteAfterDelete>
<version>0.0.1</version>
</INPUTANAME_RewriteAfterDelete>
</modules>
<global>
<models>
<inputaname_rewriteafterdelete>
<class>INPUTANAME_RewriteAfterDelete_Model</class>
</inputaname_rewriteafterdelete>
</models>
<events>
<catalog_product_delete_after>
<observers>
<inputaname_rewriteafterdelete>
<class>inputaname_rewriteafterdelete/observer</class>
<method>rewriteDelete</method>
<type>singleton</type>
</inputaname_rewriteafterdelete>
</observers>
</catalog_product_delete_after>
</events>
</global>
</config>
In app/code/ local/INPUTANAME/RewriteAfterDelete/Model/ Observer.php
<?php
class BeoService_RewriteAfterDelete_Model_Observer
{
public function rewriteDelete(Varien_Event_Observer $observer)
{
$product = $observer->getEvent()->getProduct();
$storeId = Mage::app()->getStore()->getStoreId();
$categoryIds = $product->getCategoryIds();
if(count($categoryIds) ){
$firstCategoryId = $categoryIds[0];
$category = Mage::getModel( catalog/category )->load($firstCategoryId);
if($category->getProductCount()){
$newpage = $category->getUrlPath();
}else{
$newpage = $category->getParentCategory()->getUrlPath();
}
Mage::getModel( core/url_rewrite )
->setIsSystem(0)
->setStoreId($storeId)
->setOptions( RP ) //301 redirect perm
->setTargetPath($newpage . .html )
->setRequestPath($product->getUrlPath() . .html )
->save();
}
}
}
In ./app/etc/modules/INPUTANAME_RewriteAfterDelete.xml
<?xml version="1.0" encoding="UTF-8"?>
<config>
<modules>
<INPUTANAME_RewriteAfterDelete>
<version>0.0.1</version>
</INPUTANAME_RewriteAfterDelete>
</modules>
<global>
<models>
<inputaname_rewriteafterdelete>
<class>INPUTANAME_RewriteAfterDelete_Model</class>
</inputaname_rewriteafterdelete>
</models>
<events>
<catalog_product_delete_after>
<observers>
<inputaname_rewriteafterdelete>
<class>inputaname_rewriteafterdelete/observer</class>
<method>rewriteDelete</method>
<type>singleton</type>
</inputaname_rewriteafterdelete>
</observers>
</catalog_product_delete_after>
</events>
</global>
</config>