Trailing %20 white space in URLs producing 404 errors in Codeigniter

老子叫甜甜 提交于 2021-02-19 07:16:23

问题


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?


回答1:


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.




回答2:


@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.



来源:https://stackoverflow.com/questions/60339517/trailing-20-white-space-in-urls-producing-404-errors-in-codeigniter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!