Accepting an encoded URL in a Laravel 4 route

2019-05-11 16:05发布

问题:

I'm developing a website in Laravel 4 Beta 5 and I'm trying to pass on an encoded URL to the router. The problem is, an encoded URL has percentages etc. in it, so it is blocked by Laravel. The URL is encoded with the Javascript function encodeURIComponent().

Is there a way to override Laravel so I can use any character in my route?

This is my current code:

Route::get('add/{encoded_url}', function($encoded_url)
{
    return 'The URL is: '.rawurldecode($encoded_url);
});

I have tried to override Laravel by appending where('encoded_url', '*reg-ex*');, but it didn't work (I'm not very good with reg-ex, btw).

回答1:

Give this regex a go, it will match any characters...

Route::get('add/{encoded_url}', function($encoded_url)
{
    return 'The URL is: '.rawurldecode($encoded_url);
})->where('encoded_url', '.*');


回答2:

Phill's answer is correct but I also had to make a change in my apache settings to get this working.

I had to add the following to my httpd.conf file:

AllowEncodedSlashes NoDecode

You'll need this if your are seeing an Apache 404 not found page as opposed to a Laravel NotFoundHttpException error page.

Pretty obvious explanation, but without this Apache was decoding the encoded slashes so that

http://localhost/add/http%2F%2Fwww.google.co.uk

was being routed to

http://localhost/add/http://www.google.co.uk


回答3:

urlencoded slashes do not work in Laravel due to what I consider a bug.

https://github.com/laravel/framework/pull/4323

This pull request will resolve that bug.