Search code examples
regex.htaccesshttp-redirecthttp-status-code-301

Regex htaccess rewrite to strip url prefix


So many questions come close to it, but not quite there, and I'm afraid regex makes my head spin!

After a site recode, which slightly amended some urls - which we don't want to go 404 in Google, I am looking for a 301 redirect to remap:

http://www.oursite.com/listing-product-name-1234.html

to

http://www.oursite.com/product-name-1234.html

...you can see we just want to drop "listing-". The "1234" is a unique ID per product, and the product name can be multiple words (hyphen separated) by the way.

Thanks very much for the help regex heads!


Solution

  • Enable mod_rewrite and .htaccess through httpd.conf and then put this code in your .htaccess under DOCUMENT_ROOT directory:

    Options +FollowSymLinks -MultiViews
    # Turn mod_rewrite on
    RewriteEngine On
    RewriteBase /
    
    RewriteRule ^listing-(.+?\.html)$ /$1 [L,R=301,NC]