skip to Main Content

Our URLs with a URL encoded trailing white space (%20) are producing a 404 error. The application is run on Codeigniter on Apache.

  • /directory/page%20 will return a 404 error

  • /directory/page will return a 200 OK

How can I route all URLs with a trailing %20 to the intended URL?

2

Answers


  1. @Juan Cullen, this is a common issue when you have a space before a trailing slash. For example lets say: “http://example.com/directory/page /”. you can notice the space before the trailing slash.

    To solve this for all urls that have such behavior, you can use PHP’s rtrim() function.

    Check the code below

    <?php
    
    function fix_url($url) {
        $trailing_slash = ' /'; //notice a space before the slash
        return $url = rtrim($url, $trailing_slash);
    }
    

    Now you can call it like this:

    $error_url = "http://example.com/directory/page /";
    
    $correct_url = fix_url($error_url);
    

    As you are using Codeigniter, you can put this function in a helper file and access wherever you want.

    This is an Idea try it out and let me know if it works.

    Login or Signup to reply.
  2. The problem is that some third party websites are linking to us with trailing white space in the HREF

    In that case you can add something like the following at the top of your .htaccess file to redirect (canonicalise) such requests to remove the trailing space.

    For example, before the Codeigniter front-controller:

    RewriteCond %{REQUEST_URI} s$
    RewriteRule (.*) /$1 [R=302,L]
    

    The “processed” URL-path matched by the RewriteRule pattern has already had the trailing slash removed, however, the REQUEST_URI server variable has not. So, we can check for the trailing space on the REQUEST_URI and simply redirect to “the same” (processed) URL-path, as captured by the RewriteRule pattern.

    The REQUEST_URI server variable is already %-decoded. The s shorthand character class matches against any whitespace character and the trailing $ anchors this to the end of the URL-path.

    Test first with a 302 (temporary) redirect to make sure that it works OK before changing to a 301 (permanent) redirect.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search