Redirect rules to change underscore to hyphen

Unfortunately Apache redirect only allows for 9 placeholders, so that’s the maximum amount of undercore changes that this code allows. We are using this mainly within WordPress sites, so here is the entire wp htaccess file, so you know where to position the code.

# BEGIN WordPress

RewriteEngine On
RewriteBase /

# BEGIN underscore to hyphen redirect code
RewriteRule ^([^_]*)_([^_]*)_([^_]*)_([^_]*)_([^_]*)_([^_]*)_([^_]*)_([^_]*)_([^_]*)$ /$1-$2-$3-$4-$5-$6-$7-$8-$9 [R=301,L]
RewriteRule ^([^_]*)_([^_]*)_([^_]*)_([^_]*)_([^_]*)_([^_]*)_([^_]*)_([^_]*)$ /$1-$2-$3-$4-$5-$6-$7-$8 [R=301,L]
RewriteRule ^([^_]*)_([^_]*)_([^_]*)_([^_]*)_([^_]*)_([^_]*)_([^_]*)$ /$1-$2-$3-$4-$5-$6-$7 [R=301,L]
RewriteRule ^([^_]*)_([^_]*)_([^_]*)_([^_]*)_([^_]*)_([^_]*)$ /$1-$2-$3-$4-$5-$6 [R=301,L]
RewriteRule ^([^_]*)_([^_]*)_([^_]*)_([^_]*)_([^_]*)$ /$1-$2-$3-$4-$5 [R=301,L]
RewriteRule ^([^_]*)_([^_]*)_([^_]*)_([^_]*)$ /$1-$2-$3-$4 [R=301,L]
RewriteRule ^([^_]*)_([^_]*)_([^_]*)$ /$1-$2-$3 [R=301,L]
RewriteRule ^([^_]*)_([^_]*)$ /$1-$2 [L,R=301]
# END underscore to hyphen redirect code

RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]


# END WordPress

Comments are closed.