301 Redirect to replace all spaces to hyphens

Use these rules in your .htaccess file:

Options +FollowSymlinks -MultiViews
RewriteEngine on
RewriteBase /

# keep replacing space to hyphen until there is no space use internal rewrite
RewriteRule ^([^\s%20]*)[\s%20]+(.*)$ $1-$2 [E=NOSPACE:1]

# when there is no space make an external redirection
RewriteCond %{ENV:NOSPACE} =1
RewriteRule ^([^\s%20]+)$ $1 [R=301,L]

This will replace all space characters (\s or %20) to hyphen -

So a URI of /tag/bob%20hope%20is%20funny will become /tag/bob-hope-is-funny with 301

Brief Explanation: If there are more than 1 space in URI then 1st RewriteRule is fired recursively replacing each space character with hyphen - until there is no space left. This rule will only rewrite internally.

Once no space is left 2nd RewriteRule is fired which just uses a 301 redirect to the converted URI.

Leave a Comment