RedirectLeadingSlashesSubscriber.php 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. <?php
  2. namespace Drupal\Core\EventSubscriber;
  3. use Drupal\Core\Cache\CacheableRedirectResponse;
  4. use Symfony\Component\HttpKernel\Event\GetResponseEvent;
  5. use Symfony\Component\HttpKernel\KernelEvents;
  6. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  7. /**
  8. * Redirects paths starting with multiple slashes to a single slash.
  9. */
  10. class RedirectLeadingSlashesSubscriber implements EventSubscriberInterface {
  11. /**
  12. * Redirects paths starting with multiple slashes to a single slash.
  13. *
  14. * @param \Symfony\Component\HttpKernel\Event\GetResponseEvent $event
  15. * The GetResponseEvent to process.
  16. */
  17. public function redirect(GetResponseEvent $event) {
  18. $request = $event->getRequest();
  19. // Get the requested path minus the base path.
  20. $path = $request->getPathInfo();
  21. // It is impossible to create a link or a route to a path starting with
  22. // multiple leading slashes. However if a form is added to the 404 page that
  23. // submits back to the same URI this presents an open redirect
  24. // vulnerability. Also, Drupal 7 renders the same page for
  25. // http://www.example.org/foo and http://www.example.org////foo.
  26. if (strpos($path, '//') === 0) {
  27. $path = '/' . ltrim($path, '/');
  28. $qs = $request->getQueryString();
  29. if ($qs) {
  30. $qs = '?' . $qs;
  31. }
  32. $event->setResponse(new CacheableRedirectResponse($request->getUriForPath($path) . $qs));
  33. }
  34. }
  35. /**
  36. * {@inheritdoc}
  37. */
  38. public static function getSubscribedEvents() {
  39. $events[KernelEvents::REQUEST][] = ['redirect', 1000];
  40. return $events;
  41. }
  42. }