Remove double forward slashes from URL
This tutorial explains how to remove two or more forward slashes
// from URL requests. The technique uses the
RedirectMatch directive of Apache’s
mod_alias module. Simple copy-&-paste technique.
Removing double slashes
If you’re getting URI requests that include the dreaded “double forward slash”, you’re not alone. It’s an issue that has plagued many an administrator over the years. Fortunately, the situation is simple to resolve using a tasty slice of .htaccess. All you need to do is copy the following code and place it anywhere in your site’s root .htaccess file:
# Remove double forward slashes <IfModule mod_alias.c> RedirectMatch 301 ^//(.*)$ http://example.com/$1 </IfModule>
So for example, this directive will redirect as follows:
So basically it removes the double slashes from any URL.
Logically, this code is doing the following:
- Check if the Apache module, mod_alias, is available
301server response code is specified and will be sent if a redirect happens
- Regex matches two forward slashes
//included at the beginning
^of the request
- Regex then matches any characters or no characters
- Regex matches the end of the request string
- If a URL is matched, it is redirected to the specified URL
- Any characters matched via
(.*)are appended to the URL via
That’s all there is to it. The only edit that’s required is the domain name, simply replace
http://example.com/ with your own domain and you’re good to go. Don’t forget to always test thoroughly.
Removing other slashes
If you need to remove more than one forward slash, this technique can be modified like so:
# Remove double or triple forward slashes <IfModule mod_alias.c> RedirectMatch 301 ^///?(.*)$ http://example.com/$1 </IfModule>
That will remove two or three forward slashes, if they exist in the requested URL. Remember to replace the
http://example.com/ with your own domain!
And one last bonus tip: if you need to remove slashes that are not located at the beginning of the request string, you can modify the directive something like this:
RedirectMatch 301 ^/(.*)//(.*)$ http://example.com/$1/$2/
That will remove double slashes that may appear after the first part of the request string. Here are some examples:
Slashes may be removed from other locations in the URL by replicating the pattern used in the previous example, where
$2 refer to the first and second wildcards
By combining the techniques presented in this tutorial, you can fashion a redirect to remove any number of forward slashes from anywhere in the requested URI.