Reputation: 29
I have a situation where I want to redirect all the incoming URL with %20 in the URL to be replaced with - for all occurrences.
Now I get this link -
which gives this solution
Options +FollowSymlinks -MultiViews
RewriteEngine on
RewriteCond %{THE_REQUEST} (\s|%20)
RewriteRule ^([^\s%20]+)(?:\s|%20)+([^\s%20]+)((?:\s|%20)+.*)$ $1-$2$3 [N,DPI]
RewriteRule ^([^\s%20]+)(?:\s|%20)+(.*)$ /$1-$2 [L,R=301,DPI]
which works perfect but there is one small issue with this solution. This also redirects the request for images/docs/pdf or other resources and results in 404
Can i have something which will redirect only certain sections and not all incoming links like it will replace and redirect only for
www.test.com/colleges/this%20is%20my%20link/123 to
www.test.com/colleges/this-is-my-link/123
or
www.test.com/schools/this%20is%20my%20link/123 to
www.test.com/schools/this-is-my-link/123
and leave all other requests intact??
Upvotes: 2
Views: 1510
Reputation: 785128
Change your code to this:
RewriteRule \.(jpe?g|png|gif|ico|bmp|pdf|docx?|txt|css|js)$ - [L,NC]
RewriteRule ^([^\s%20]+)(?:\s|%20)+([^\s%20]+)((?:\s|%20)+.*)$ $1-$2$3 [N,DPI]
RewriteRule ^([^\s%20]+)(?:\s|%20)+(.*)$ /$1-$2 [L,R=301,DPI]
Upvotes: 1
Reputation: 7074
That all seems awfully complex for what you want to do. In theory (!!) apache should unescape the %20
characters and replace them with a space in the string you're trying to match, so the following should work:
RewriteRule ^([^\ ]+)\ (.*)$ $1-$2 [N]
It basically splits any requested URI into non-space character, followed by space, followed by anything, and rewrites the space to be a -
. It then repeats all rewrites ([N]
) so that it can replace the next space, until it doesn't match.
If the issue is that sometimes you have an actual file that has spaces, and you want to access that, just prefix with a condition that states it will only do the redirect if you're not accessing an actual file:
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^([^\ ]+)\ (.*)$ $1-$2 [N]
Upvotes: 0