RedirectMatch las URL del producto antiguo (sin ID) a la nueva URL con estructura básica (usando ID)

May 08 2019

Estoy enfrentando un problema con nuestra instalación de PrestaShop 1.7.5.

Hace aproximadamente 2 semanas, intenté actualizar nuestra versión de PrestaShop (de 1.7.4 a 1.7.5). Desafortunadamente, 1 módulo importante ya no funciona (la anulación del despachador está desactualizada), este módulo genera URL compatibles con SEO, sin ID en la URL, como esta:domain/{category}/{rewrite}

Preferimos no hacer retroceso y estamos considerando dos opciones.

Opción 1: Redirigir todas las URL de productos antiguos a las nuevas URL

Formato de URL antiguo: domain/{category}/{rewrite}

Nuevo formato de URL: domain/{parent-category}/{sub-category}/{ID}-{ID_product_attribute}-{rewrite}

Opción 2: Redirigir todos los 404 a searchcontroller

Al usar las palabras clave de la URL, para lograr esto, podemos usar la parte {category}&{rewrite}

Probé muchos códigos pequeños, que encontré en la red, como este:

RewriteRule ^search/?$ / [R=301,L] RewriteRule ^search/([^/]+)/?$ /search/$1/1/ [R=301,L] RewriteRule ^search/([^/]+)/([0-9]+)/?$ search.php?q=$1&category=web&d=$2 [NC,L]

Leí el manual en https://httpd.apache.org/docs/2.4/mod/mod_rewrite.html Entiendo cómo redirigir una página simple a otra ... pero me atasco ...

Este es mi archivo .htacces tal como está ahora (generado por prestashop):


# ~~start~~ Do not remove this comment, Prestashop will keep automatically the code outside this comment when .htaccess will be generated again
# .htaccess automaticaly generated by PrestaShop e-commerce open-source solution
# http://www.prestashop.com - http://www.prestashop.com/forums

<IfModule mod_rewrite.c>
<IfModule mod_env.c>
SetEnv HTTP_MOD_REWRITE On
</IfModule>

RewriteEngine on

#Domain: domain.be
RewriteRule . - [E=REWRITEBASE:/]
RewriteRule ^api$ api/ [L] RewriteRule ^api/(.*)$ %{ENV:REWRITEBASE}webservice/dispatcher.php?url=$1 [QSA,L] # Images RewriteCond %{HTTP_HOST} ^domain.be$
RewriteRule ^([0-9])(\-[_a-zA-Z0-9-]*)?(-[0-9]+)?/.+\.jpg$ %{ENV:REWRITEBASE}img/p/$1/$1$2$3.jpg [L] RewriteCond %{HTTP_HOST} ^domain.be$
RewriteRule ^([0-9])([0-9])(\-[_a-zA-Z0-9-]*)?(-[0-9]+)?/.+\.jpg$ %{ENV:REWRITEBASE}img/p/$1/$2/$1$2$3$4.jpg [L] RewriteCond %{HTTP_HOST} ^domain.be$
RewriteRule ^([0-9])([0-9])([0-9])(\-[_a-zA-Z0-9-]*)?(-[0-9]+)?/.+\.jpg$ %{ENV:REWRITEBASE}img/p/$1/$2/$3/$1$2$3$4$5.jpg [L] RewriteCond %{HTTP_HOST} ^domain.be$
RewriteRule ^([0-9])([0-9])([0-9])([0-9])(\-[_a-zA-Z0-9-]*)?(-[0-9]+)?/.+\.jpg$ %{ENV:REWRITEBASE}img/p/$1/$2/$3/$4/$1$2$3$4$5$6.jpg [L] RewriteCond %{HTTP_HOST} ^domain.be$
RewriteRule ^([0-9])([0-9])([0-9])([0-9])([0-9])(\-[_a-zA-Z0-9-]*)?(-[0-9]+)?/.+\.jpg$ %{ENV:REWRITEBASE}img/p/$1/$2/$3/$4/$5/$1$2$3$4$5$6$7.jpg [L] RewriteCond %{HTTP_HOST} ^domain.be$
RewriteRule ^([0-9])([0-9])([0-9])([0-9])([0-9])([0-9])(\-[_a-zA-Z0-9-]*)?(-[0-9]+)?/.+\.jpg$ %{ENV:REWRITEBASE}img/p/$1/$2/$3/$4/$5/$6/$1$2$3$4$5$6$7$8.jpg [L] RewriteCond %{HTTP_HOST} ^domain.be$
RewriteRule ^([0-9])([0-9])([0-9])([0-9])([0-9])([0-9])([0-9])(\-[_a-zA-Z0-9-]*)?(-[0-9]+)?/.+\.jpg$ %{ENV:REWRITEBASE}img/p/$1/$2/$3/$4/$5/$6/$7/$1$2$3$4$5$6$7$8$9.jpg [L] RewriteCond %{HTTP_HOST} ^domain.be$
RewriteRule ^([0-9])([0-9])([0-9])([0-9])([0-9])([0-9])([0-9])([0-9])(\-[_a-zA-Z0-9-]*)?(-[0-9]+)?/.+\.jpg$ %{ENV:REWRITEBASE}img/p/$1/$2/$3/$4/$5/$6/$7/$8/$1$2$3$4$5$6$7$8$9$10.jpg [L] RewriteCond %{HTTP_HOST} ^domain.be$
RewriteRule ^c/([0-9]+)(\-[\.*_a-zA-Z0-9-]*)(-[0-9]+)?/.+\.jpg$ %{ENV:REWRITEBASE}img/c/$1$2$3.jpg [L]
RewriteCond %{HTTP_HOST} ^domain.be$ RewriteRule ^c/([a-zA-Z_-]+)(-[0-9]+)?/.+\.jpg$ %{ENV:REWRITEBASE}img/c/$1$2.jpg [L]
# AlphaImageLoader for IE and fancybox
RewriteRule ^images_ie/?([^/]+)\.(jpe?g|png|gif)$ js/jquery/plugins/fancybox/images/$1.$2 [L] # Dispatcher RewriteCond %{REQUEST_FILENAME} -s [OR] RewriteCond %{REQUEST_FILENAME} -l [OR] RewriteCond %{REQUEST_FILENAME} -d RewriteRule ^.*$ - [NC,L]
RewriteRule ^.*$ %{ENV:REWRITEBASE}index.php [NC,L] </IfModule> AddType application/vnd.ms-fontobject .eot AddType font/ttf .ttf AddType font/otf .otf AddType application/font-woff .woff AddType font/woff2 .woff2 <IfModule mod_headers.c> <FilesMatch "\.(ttf|ttc|otf|eot|woff|woff2|svg)$">
        Header set Access-Control-Allow-Origin "*"
    </FilesMatch>
</IfModule>

<IfModule mod_expires.c>
    ExpiresActive On
    ExpiresByType image/gif "access plus 1 month"
    ExpiresByType image/jpeg "access plus 1 month"
    ExpiresByType image/png "access plus 1 month"
    ExpiresByType text/css "access plus 1 week"
    ExpiresByType text/javascript "access plus 1 week"
    ExpiresByType application/javascript "access plus 1 week"
    ExpiresByType application/x-javascript "access plus 1 week"
    ExpiresByType image/x-icon "access plus 1 year"
    ExpiresByType image/svg+xml "access plus 1 year"
    ExpiresByType image/vnd.microsoft.icon "access plus 1 year"
    ExpiresByType application/font-woff "access plus 1 year"
    ExpiresByType application/x-font-woff "access plus 1 year"
    ExpiresByType font/woff2 "access plus 1 year"
    ExpiresByType application/vnd.ms-fontobject "access plus 1 year"
    ExpiresByType font/opentype "access plus 1 year"
    ExpiresByType font/ttf "access plus 1 year"
    ExpiresByType font/otf "access plus 1 year"
    ExpiresByType application/x-font-ttf "access plus 1 year"
    ExpiresByType application/x-font-otf "access plus 1 year"
</IfModule>

<IfModule mod_headers.c>
    Header unset Etag
</IfModule>
FileETag none
<IfModule mod_deflate.c>
    <IfModule mod_filter.c>
        AddOutputFilterByType DEFLATE text/html text/css text/javascript application/javascript application/x-javascript font/ttf application/x-font-ttf font/otf application/x-font-otf font/opentype image/svg+xml
    </IfModule>
</IfModule>

#If rewrite mod isn't enabled
ErrorDocument 404 /index.php?controller=404

# ~~end~~ Do not remove this comment, Prestashop will keep automatically the code outside this comment when .htaccess will be generated again

¡Gracias por adelantado!

Respuestas

BrunoLeveque May 09 2019 at 16:50

Esto funciona y redirigirá permanentemente las URL de los productos antiguos a las nuevas (opción n. ° 1):

  1. Coloque el siguiente script en su carpeta raíz de PrestaShop
  2. Opcional: edite los parámetros id_shopy id_langpara que coincidan con su configuración
  3. Ejecútelo y copie / pegue el resultado en su archivo .htaccess, justo después RewriteEngine on, elimine el script
  4. ¡Voilà!

Guión:

<?php

include('config/config.inc.php');
include('init.php');

$context = Context::getContext(); $products = Db::getInstance()->ExecuteS('
SELECT p.id_product, pl.link_rewrite prod_url, cl.link_rewrite cat_url
FROM '._DB_PREFIX_.'product p
LEFT JOIN '._DB_PREFIX_.'product_lang pl ON (pl.id_product = p.id_product)
LEFT JOIN '._DB_PREFIX_.'category_lang cl ON (cl.id_category = p.id_category_default)
WHERE p.active = 1 AND cl.id_lang = 1 AND cl.id_shop = 1 AND pl.id_lang = 1 AND cl.id_shop = 1');

foreach ($products as $p)
{
    $new_url = $context->link->getProductLink(new Product((int)$p['id_product'])); echo 'RewriteRule ^'.$p['cat_url'].'/'.$p['prod_url'].'$ '.$new_url.' [L,R=301]<br />';
}

Salida (en una tienda de demostración de PrestaShop con solo 2 productos):

RewriteRule ^men/hummingbird-printed-t-shirt$ http://localhost/prestashop/1-hummingbird-printed-t-shirt.html [L,R=301]
RewriteRule ^women/brown-bear-printed-sweater$ http://localhost/prestashop/2-brown-bear-printed-sweater.html [L,R=301]

Archivo .htaccess después de copiar / pegar:

...
<IfModule mod_rewrite.c>
<IfModule mod_env.c>
SetEnv HTTP_MOD_REWRITE On
</IfModule>

RewriteEngine on

# Permanent redirections
RewriteRule ^men/hummingbird-printed-t-shirt$ http://localhost/prestashop/1-hummingbird-printed-t-shirt.html [L,R=301]
RewriteRule ^women/brown-bear-printed-sweater$ http://localhost/prestashop/2-brown-bear-printed-sweater.html [L,R=301] #Domain: localhost RewriteRule . - [E=REWRITEBASE:/prestashop/] RewriteRule ^api$ api/ [L]
...

La opción # 2 no me parece viable en términos de tasa de conversión.

¡Espero que esto ayude!

Si no es así, le pediría al desarrollador del módulo una versión actualizada, $ 25 parece un costo razonable para actualizar dado el tiempo que le llevaría a usted.

MahdiShad May 09 2019 at 10:25

Dado que las ID de producto se han eliminado de sus URL, creo que no puede redirigirlas a través de Htaccess. consejo: no puede agregar sus reglas de URL línea por línea en el archivo htaccess. Ralentizará su sitio. Todas las reglas se verifican a cualquier solicitud de su sitio (enlaces css, enlaces js, imágenes, etc.)

Para hacer esto, necesita tener un nuevo controlador que verifique y redirija las URL. De hecho, necesita otro módulo para solucionar este problema. Su anulación debe revertirse.

- Es por eso que nunca aconsejamos a nuestros clientes que eliminen la identificación de las URL de PrestaShop.