Justin Nunn Justin Nunn - 10 months ago 71
Apache Configuration Question

301 Redirects Rewrite Rule to replace underscore with hyphen and remove subdirectory

I need help creating a rewrite rule/301 redirect for the following link structures in the .httaccess folder.

Source URL: www.example.com/sub_directory/product_name_1.html

Destination URL: www.example.com/prodcut-name-1.html

The requirements for the redirect then are as follows:

  • Remove /sub_directory/

  • Change all underscores '_' to hyphens '-'

Unfortunately my regex isn't very good. I've tried searching around and but the solutions from other post with similar issues where not working for me (such as here)

Any help on a solution for this would be much appreciated. Also if you could please explain the why/how of it. I'd like to be able to better understand this.

Answer Source

You can use these rules on top of your site root .htaccess:

RewriteEngine On

RewriteRule ^(sub_directory/[^_]*)_+(.*)$ $1-$2 [NC,N,DPI]
RewriteRule ^sub_directory/(.*)$ /$1 [R=301,NC,NE,L]

# rest of your rules go here