Justin Nunn
Justin Nunn

Reputation: 23

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:

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.

Upvotes: 2

Views: 1271

Answers (2)

anubhava
anubhava

Reputation: 785276

Answer from @Walf is close but requires some changes e.g. regex anchors and DPI flag.

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

RewriteEngine On

# remove /sub_directory/ when there is no _ left
RewriteRule ^sub_directory/([^_]+)$ /$1 [R=301,NC,NE,L]

# use recursion based rule to replace _ by -
RewriteRule ^(sub_directory/[^_]*)_+(.*)$ $1-$2 [NC,N,DPI]

# rest of your rules go here

Upvotes: 1

Walf
Walf

Reputation: 9318

Something like this

RewriteEngine on
RewriteBase /
RewriteRule ^(sub_directory/[^_]*)_+(.*) $1-$2 [DPI,N]
RewriteRule ^sub_directory(?:$|/(.*)) http://%{HTTP_HOST}/$1 [R=301,L]

It first loops through URLs that are in that subdirectory, to replace consecutive underscores with a single hyphen. It's done first so it doesn't interfere with other URLs that may contain an underscore. It then externally redirects (the cleaned) requests for that subdirectory to the root. The ugly grouping makes sure it only applies to exactly that folder.

Upvotes: 1

Related Questions