Consider an .htaccess
file which must convert all underscores to dashes, and replace a potential .html
suffix with a slash in the filename.
Example URL from client: http://foo.com/a_b/c_d.html
Example URL to redirect: http://foo.com/a-b/c-d/
I have been using this rule to replace the .html
suffix:
RewriteRule ^(.*)\.html$ $1/ [R,L]
I have found this terrific serverfault.SE post for the underscore rewriting:
RewriteRule ^(.*)_(.*)_(.*)_(.*)$ /$1-$2-$3-$4 [R,L]
RewriteRule ^(.*)_(.*)_(.*)$ /$1-$2-$3 [R,L]
RewriteRule ^(.*)_(.*)$ /$1-$2 [R,L]
However, only one of the replacement types happens, whichever is first in the .htaccess
file. I cannot seem to configure .htaccess
to perform both replacements.
That means that the following code will replace the .html
suffix only:
RewriteRule ^(.*)\.html$ $1/ [R,L]
RewriteRule ^(.*)_(.*)_(.*)_(.*)$ /$1-$2-$3-$4 [R,L]
RewriteRule ^(.*)_(.*)_(.*)$ /$1-$2-$3 [R,L]
RewriteRule ^(.*)_(.*)$ /$1-$2 [R,L]
And the following code will replace underscores only:
RewriteRule ^(.*)_(.*)_(.*)_(.*)$ /$1-$2-$3-$4 [R,L]
RewriteRule ^(.*)_(.*)_(.*)$ /$1-$2-$3 [R,L]
RewriteRule ^(.*)_(.*)$ /$1-$2 [R,L]
RewriteRule ^(.*)\.html$ $1/ [R,L]
How must .htaccess
be configured to replace both the .html
suffix and the underscores?