getQueryString()) { $target .= '?'.$qs; } $method = strtoupper($request->method()); $followRedirects = $method === 'GET' || $method === 'HEAD'; $client = Http::withOptions([ 'allow_redirects' => $followRedirects ? ['max' => 5] : false, ])->timeout(15); $pending = match ($method) { 'POST' => $client->withHeaders($this->forwardHeaders($request))->asForm()->post($target, $request->post()), 'PATCH' => $client->withHeaders($this->forwardHeaders($request))->patch($target, $request->all()), 'DELETE' => $client->withHeaders($this->forwardHeaders($request))->delete($target), default => $client->withHeaders($this->forwardHeaders($request))->get($target), }; $upstream = $pending->toPsrResponse(); $response = new Response( (string) $upstream->getBody(), $upstream->getStatusCode(), $this->sanitizeHeaders($upstream->getHeaders()) ); if ($response->isRedirection()) { $location = $response->headers->get('Location'); if (is_string($location)) { $response->headers->set('Location', $this->rewriteLocation($location, $slug)); } } return $response; } /** @return array */ private function forwardHeaders(Request $request): array { $headers = []; foreach (['Accept', 'Accept-Language', 'User-Agent', 'Referer'] as $name) { $value = $request->header($name); if ($value !== null) { $headers[$name] = $value; } } return $headers; } /** @param array> $headers */ private function sanitizeHeaders(array $headers): array { $flat = []; foreach ($headers as $name => $values) { if (strtolower($name) === 'transfer-encoding') { continue; } $flat[$name] = $values[0] ?? ''; } return $flat; } private function rewriteLocation(string $location, string $slug): string { $platform = rtrim((string) config('app.platform_url', 'https://ladill.com'), '/'); $prefix = $platform.'/q/'.$slug; if (str_starts_with($location, $prefix)) { $suffix = substr($location, strlen($prefix)); $rewritten = LadillLink::url($slug).$suffix; return $rewritten; } return $location; } }