Laravel SSRF Prevention: Secure Outbound HTTP Requests
A practical guide to defending outbound Laravel HTTP requests against redirects, DNS changes and internal-network access.
Laravel makes outgoing HTTP requests pleasantly simple. That convenience can become dangerous when a user, third-party integration, or automation rule controls the destination URL. A compromised destination may point a server-side request toward an internal service or cloud metadata endpoint. This is server-side request forgery (SSRF): a security risk for link previews, file importers, webhook delivery systems and background queue workers.
This guide explains how Laravel developers can reduce SSRF risks with trusted destinations, request controls, network restrictions and realistic tests. It follows the OWASP SSRF Prevention Cheat Sheet and the official Laravel HTTP Client documentation. No single URL validator or HTTP-client flag provides complete protection.

Why SSRF matters even for small Laravel apps
A URL preview tool looks harmless: a visitor submits a link, your server fetches it, and the application extracts a title. Yet your PHP worker is not an ordinary public browser. Depending on the network, it may reach loopback interfaces, database administration panels, private container addresses and cloud metadata services that are unreachable from the internet.
The same problem can appear in an invoicing integration that accepts callback destinations, a CRM that imports remote avatars, or a queued job that downloads user-provided reports. Moving the HTTP request into a queue changes when and where it runs; it does not make an untrusted URL safer.
The unsafe shortcut
The following is an anti-pattern, shown only to explain the risk. It should not be used in a production controller:
// Unsafe: the requester controls the whole destination.
$url = $request->input('url');
$response = Http::get($url);
return $response->body();
Requiring an https:// prefix is not a sufficient fix. The host may be attacker-controlled, resolve to a sensitive address, or return a redirect. A successful TLS connection does not mean the destination is authorized.
The strongest design: do not accept a destination URL
If a feature only communicates with a known partner API, keep its origin in trusted server-side configuration and accept only the data required for that operation. For example, an order lookup needs an order identifier, not a complete URL. This removes most destination ambiguity and makes the integration easier to review.
use Illuminate\Support\Facades\Http;
// Replace this reserved example hostname with your vetted API.
$input = $request->validate([
'order_id' => ['required', 'uuid'],
]);
$response = Http::acceptJson()
->connectTimeout(2)
->timeout(5)
->withoutRedirecting()
->get('https://api.partner.example/v1/orders/' . $input['order_id']);
The reserved .example domain is illustrative, not a working endpoint. Never let a user overwrite the configured origin through a normal form field. Keep partner credentials out of the URL and protect configuration updates with appropriate access control.
When arbitrary public URLs are a real requirement
Some products genuinely need to fetch arbitrary websites. Treat that as a high-risk subsystem rather than adding a broad exception to the main application's HTTP client. Use a carefully specified scheme and port policy, a maintained URL parser, destination validation and a restricted outbound network. Reject URLs containing embedded credentials or unsupported protocols. Keep the fetcher separate from database and administration networks wherever possible.
Prefer allowlists to brittle deny-lists
When your application knows its partner systems, use a positive allowlist of exact, canonical destination hosts and ports. Avoid substring comparisons: merely finding a trusted brand name somewhere inside a hostname does not authenticate the host. Validate the parsed host, not the raw text of the entire URL.
OWASP warns that deny-lists of suspicious strings and a handful of internal addresses are bypass-prone. IPv4 and IPv6 have multiple address families, and network transformations can make two textual representations refer to the same destination. A robust system normalizes addresses and enforces policy at the network connection, not only at form submission.
DNS rebinding and time-of-check/time-of-use
A hostname can return several A or AAAA records. DNS answers can also change between the moment an application validates a name and the moment its HTTP client opens a connection. Checking one address and allowing a later independent resolution is not a strong guarantee. Where arbitrary fetching is unavoidable, use a controlled egress proxy or client architecture that validates and binds the actual connection target. Test this behavior explicitly.
Cloud metadata services deserve particular care because they may expose credentials or instance configuration. Use workload-level egress controls and platform-specific protections such as metadata-service hardening. Those controls provide defense in depth; they do not replace a clear destination policy.
Disable automatic redirects for risky requests
Even a URL on an approved host can send a redirect. If the client follows that redirect without repeating the destination checks, a request may leave the approved network boundary. Laravel exposes withoutRedirecting(), along with timeout() and connectTimeout(), to help control outgoing requests.
$response = Http::acceptJson()
->withoutRedirecting()
->connectTimeout(2)
->timeout(5)
->get('https://api.partner.example/v1/status');
if ($response->redirect()) {
// Stop and investigate an unexpected location change.
}
This is a guardrail, not an SSRF firewall. Redirect control does not prevent an allowed hostname from resolving to an inappropriate address. Never turn off TLS certificate verification to conceal upstream configuration errors.
Secure your queue workers and webhook integrations
Background jobs are commonly granted broad network access. They also execute later, when settings and DNS results may have changed. Re-apply destination policy at execution time instead of assuming an earlier controller validation is sufficient. Keep outbound network permissions consistent across PHP-FPM, CLI tasks, scheduled commands and long-running workers.
Retries require separate thought. A timeout does not prove an upstream operation failed to execute. Use bounded retry budgets and idempotency rules for operations that can create payments, orders or other side effects. The Laravel webhook idempotency and retry-safe processing guide covers duplicate deliveries from the receiving side and offers related design principles for integrations.
Bound response sizes as well as time
Connection and total timeouts limit waiting but do not automatically limit downloaded bytes. Streaming downloads should enforce a maximum body size, concurrency limits and a trusted content-processing path. A remote server may claim a misleading Content-Type header. Protect image decoders, document extractors and archive processors independently from URL validation.
Test the security boundary, not just string validation
Laravel's Http::fake() and request tests can verify which URLs your application constructs, how it handles non-success responses and whether invalid inputs dispatch jobs. Complement these with isolated integration tests that confirm the network itself blocks disallowed targets. Do not run tests against real internal admin services or cloud metadata endpoints.
Suggested negative test cases
Reject malformed URLs, unsupported schemes, unexpected ports, user-information components, unknown integration IDs and hostname lookalikes. In a safe test environment, simulate redirects, multiple DNS answers and changes between validation and connection. Include IPv6, mapped address forms and different execution contexts. Check that untrusted destinations are permanently rejected rather than endlessly retried.
Failure handling and observability
Record safe metadata such as integration ID, policy decision, timeout category and request correlation ID. Do not log authorization tokens, complete signed URLs or sensitive response bodies. Alert on unusual concentrations of denied destinations, redirect responses and repeated connection failures. Keep error messages informative for operators without exposing private network information to clients.
A practical VPS rollout checklist
Start by inventorying outgoing requests in controllers, queued jobs and scheduled commands. Identify who controls each hostname and port. Record trusted partners and separate them from genuine public-web fetching. Restrict the latter behind a dedicated proxy or service with explicit network permissions.
Review PHP-FPM pool and queue-worker settings independently, then deploy to staging with representative network routes. Preserve a rollback path. The PHP 8.6 and Laravel compatibility checklist illustrates why a successful CLI test does not guarantee identical web-worker behavior.
Use a controlled development environment for these changes rather than diagnosing from production alone. Rubic8's cloud development sandbox cost and safety guide provides a complementary operational checklist. When reviewing JSON configuration or third-party response samples, the Rubic8 JSON validator can check formatting, but syntactic correctness never makes external input trustworthy.
Common SSRF mistakes to avoid
Trusting HTTPS alone: encryption is not destination authorization. Filtering only localhost: internal services use many address ranges and forms. Validating only when a job is queued: execution can occur after settings change. Following redirects by default: each redirect can change the destination. Over-trusting framework helpers: Laravel's HTTP client is a request abstraction, not a complete security perimeter.
Defense in depth: the production architecture
Combine a trusted integration registry, fixed server-owned destinations, strict validation, connection-time routing enforcement, restricted outbound networking, bounded HTTP usage and useful failure telemetry. If arbitrary fetching is central to your product, isolate it from the main SaaS workload so a mistake cannot expose unrelated services.

The most useful first audit is simple: search your application for outbound HTTP calls and list who controls each request's hostname. If any ordinary user or untrusted partner can choose that hostname, review the feature before shipping more functionality.
Primary sources
This editorial guide is grounded in OWASP's prevention guidance, Laravel's HTTP Client reference and the PendingRequest API documentation. Check the methods available in your specific Laravel version.
Rubic8 Editorial Team
Editorial Team
Rubic8 creates practical guides and free tools for developers, webmasters, and digital publishers. Our fast-changing technical content is reviewed against current primary documentation before publication.