Skip to content

Instantly share code, notes, and snippets.

@mauriciopazpp
Last active April 2, 2019 19:39
Show Gist options
  • Save mauriciopazpp/ed91109b38d66b9eb10c1093bc62a389 to your computer and use it in GitHub Desktop.
Save mauriciopazpp/ed91109b38d66b9eb10c1093bc62a389 to your computer and use it in GitHub Desktop.
Duplicate entries core_url_rewrite magento 1

How to find the duplicate entries:

select * from core_url_rewrite WHERE is_system <> 1 AND id_path REGEXP "^[0-9]+_[0-9]+$" AND (request_path REGEXP ".*-[0-9]*\.html" OR target_path = request_path)

Delete all the duplicate entries:

DELETE FROM core_url_rewrite 
WHERE is_system <> 1 AND id_path REGEXP "^[0-9]+_[0-9]+$" AND
      (request_path REGEXP ".*-[0-9]*\.html" 
          OR target_path = request_path)

Apply the patch

diff -rupN mage_org/app/code/core/Mage/Catalog/Model/Url.php src_shop/app/code/core/Mage/Catalog/Model/Url.php
--- mage_org/app/code/core/Mage/Catalog/Model/Url.php   2013-11-19 00:48:25.679009391 +0100
+++ src_shop/app/code/core/Mage/Catalog/Model/Url.php   2013-11-19 00:49:24.188005601 +0100
@@ -643,13 +643,24 @@ class Mage_Catalog_Model_Url
                 $this->_rewrite = $rewrite;
                 return $requestPath;
             }
+
+            // avoid unnecessary creation of new url_keys for duplicate url keys
+            $noSuffixPath = substr($requestPath, 0, -(strlen($suffix)));
+            $regEx = '#^('.preg_quote($noSuffixPath).')(-([0-9]+))?('.preg_quote($suffix).')#i';
+            $currentRewrite = $this->getResource()->getRewriteByIdPath($idPath, $storeId);
+            if ($currentRewrite && preg_match($regEx, $currentRewrite->getRequestPath(), $match)) {
+                $this->_rewrite = $currentRewrite;
+                return $currentRewrite->getRequestPath();
+            }
+
             // match request_url abcdef1234(-12)(.html) pattern
             $match = array();
             $regularExpression = '#^([0-9a-z/-]+?)(-([0-9]+))?('.preg_quote($suffix).')?$#i';
             if (!preg_match($regularExpression, $requestPath, $match)) {
                 return $this->getUnusedPath($storeId, '-', $idPath);
             }
-            $match[1] = $match[1] . '-';
+            $match[1] = $noSuffixPath . '-'; // always use full prefix of url_key
+            unset($match[3]); // don't start counting with a possible number in the url_key
             $match[4] = isset($match[4]) ? $match[4] : '';

             $lastRequestPath = $this->getResource()

Save the code above in a file, and run:

patch -p1 magento_url_rewrite.patch

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment