Weave Code
Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Laravel Force Host Laravel Package

14four/laravel-force-host

Middleware for Laravel that forces a single canonical host for all requests. Automatically redirects to your configured domain (and optionally scheme), preventing duplicate URLs across www/non-www and improving SEO, cache consistency, and security.

View on GitHub
Deep Wiki
Context7

Technical Evaluation

Architecture Fit

  • Purpose Alignment: The package directly addresses host header poisoning (a security vulnerability where attackers manipulate the Host header to bypass security controls, perform SSRF, or route traffic maliciously). This is critical for APIs, multi-tenant apps, or systems exposed to untrusted networks (e.g., public-facing Laravel apps, microservices).
  • Security Layer: Acts as a defense-in-depth measure alongside existing protections (e.g., Laravel’s built-in trustedProxies, force_https, or middleware like App\Http\Middleware\TrustProxies).
  • Minimalism: Lightweight (~50 LOC) with a single middleware, making it non-intrusive to existing Laravel architecture. Ideal for teams prioritizing security without heavy refactoring.

Integration Feasibility

  • Laravel Native: Designed for Laravel’s middleware pipeline (PSR-15 compliant), requiring zero framework changes. Integrates seamlessly with:
    • app/Http/Kernel.php (middleware stack).
    • Existing trustedProxies or VerifyCsrfToken middleware.
  • Configuration Override: Supports dynamic host enforcement via .env (FORCE_HOST=example.com), enabling environment-specific policies (e.g., dev/staging/prod).
  • Reverse Proxy Compatibility: Works with Nginx/Apache when X-Forwarded-Host is present (configurable via trustedProxies).

Technical Risk

Risk Area Assessment Mitigation Strategy
False Positives Overly strict host enforcement may break multi-tenant or subdomain setups. Test with FORCE_HOST=*.example.com or whitelist patterns (e.g., regex).
Performance Minimal overhead (single regex check), but adds middleware latency. Benchmark in staging; negligible for most apps (<0.1ms).
Proxy Misconfiguration If trustedProxies misconfigured, X-Forwarded-Host may be ignored. Validate proxy headers in middleware; log warnings for mismatches.
Edge Cases Wildcard subdomains or dynamic hosts (e.g., *.user-*.example.com). Extend package to support callback validation (e.g., ForceHost::validate($host)).

Key Questions

  1. Use Case Clarity:
    • Is this for public APIs, internal services, or multi-tenant SaaS? (Affects host whitelisting strategy.)
    • Are you using reverse proxies (e.g., Nginx, Cloudflare)? If so, how are X-Forwarded-* headers configured?
  2. Existing Protections:
    • Do you already use trustedProxies or VerifyCsrfToken? How does this package complement them?
    • Are there custom middleware that might conflict with host validation?
  3. Deployment Model:
    • Is this for all environments (dev/prod) or just production?
    • How will you test host enforcement without breaking local development?
  4. Monitoring:
    • Do you have logging for blocked requests? (Package lacks built-in logging; may need extension.)
    • How will you alert on host poisoning attempts?

Integration Approach

Stack Fit

  • Laravel Ecosystem: Perfect fit for Laravel 5.5+ (composer-based, PSR-15 middleware).
  • Proxy Environments: Critical for:
    • Docker/Kubernetes: Where host headers may be spoofed in service meshes.
    • Cloud (AWS ALB, GCP Load Balancer): Multi-region setups with dynamic host routing.
    • Edge Networks (Cloudflare, Fastly): Where Host headers can be tampered with at the CDN layer.
  • Non-Laravel PHP: Not applicable (hard dependency on Laravel’s middleware pipeline).

Migration Path

  1. Installation:

    composer require 14four/laravel-force-host
    
    • No database/migrations or service provider changes required.
  2. Configuration:

    • Add to app/Http/Kernel.php:
      protected $middleware = [
          \App\Http\Middleware\ForceHost::class, // Add to global middleware
          // ... other middleware
      ];
      
    • Or register conditionally (e.g., only in production):
      if (app()->environment('production')) {
          $middleware[] = \App\Http\Middleware\ForceHost::class;
      }
      
  3. Environment Setup:

    • Define FORCE_HOST in .env:
      FORCE_HOST=api.example.com
      
    • For wildcards/subdomains:
      FORCE_HOST=*.example.com
      
  4. Testing:

    • Unit Test Middleware:
      public function test_host_validation()
      {
          $request = new Request(['Host' => 'evil.com']);
          $middleware = new ForceHost();
          $middleware->handle($request, function () {})->then(function () {
              $this->fail('Should have blocked invalid host');
          });
      }
      
    • Integration Test:
      • Use Laravel’s actingAs() or Http::fake() to simulate spoofed hosts.
      • Verify 403 responses for invalid hosts.

Compatibility

Component Compatibility Notes
Laravel Version Tested on Laravel 5.5+ (PHP 7.2+). No breaking changes expected for newer versions.
PHP Version Requires PHP 7.2+ (for named arguments in middleware).
Middleware Order Must run before routing middleware (e.g., SubdomainMiddleware).
Proxy Headers Respects X-Forwarded-Host if trustedProxies is configured.
Custom Hosts Extendable via ForceHost::extend() for dynamic validation logic.

Sequencing

  1. Phase 1: Sandbox Testing

    • Deploy in a non-production environment with FORCE_HOST set to a single domain.
    • Monitor logs for false positives (e.g., health checks, internal services).
  2. Phase 2: Gradual Rollout

    • Add to staging with FORCE_HOST=*.staging.example.com.
    • Use feature flags or environment checks to toggle middleware.
  3. Phase 3: Production Hardening

    • Restrict to production-only (app()->environment('production')).
    • Combine with WAF rules (e.g., Cloudflare Host Header checks) for redundancy.
  4. Phase 4: Monitoring & Alerting

    • Log blocked requests (extend middleware to emit events).
    • Set up alerts for repeated host poisoning attempts.

Operational Impact

Maintenance

  • Low Effort:
    • No database schema changes or cron jobs.
    • Configuration-driven (.env updates suffice for most changes).
  • Upgrade Path:
    • Monitor for Laravel version compatibility (e.g., if middleware signature changes).
    • Fork if package becomes abandoned (minimal codebase).

Support

  • Debugging:
    • False Negatives: Ensure trustedProxies is correctly configured for X-Forwarded-Host.
    • False Positives: Use FORCE_HOST=*.example.com or implement custom validation callbacks.
  • Troubleshooting Steps:
    1. Verify middleware is registered in Kernel.php.
    2. Check .env for correct FORCE_HOST value.
    3. Test with curl -H "Host: evil.com" http://your-app (should return 403).
    4. Review proxy headers if using reverse proxies.

Scaling

  • Performance:
    • Stateless: No database or external dependencies; scales horizontally with Laravel.
    • Regex Overhead: Minimal (host validation is a single preg_match).
    • Benchmark: Test under load (e.g., 10k RPS) to confirm negligible latency.
  • Distributed Systems:
    • Works seamlessly in microservices (each service enforces its own host).
    • Pair with service mesh policies (e.g., Istio virtual hosts) for multi-cluster setups.

Failure Modes

Failure Scenario Impact Mitigation
Middleware Not Registered No host validation. CI/CD check for ForceHost in Kernel.php.
Incorrect FORCE_HOST Overly permissive/blocking. Validate .env via CI (e.g., regex pattern).
Proxy Misconfiguration X-Forwarded-Host ignored. Log warnings if X-Forwarded-Host present but trustedProxies misconfigured.
Regex DoS Malicious hosts
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
mehedimi/laravel-amp-mail
happones/laravel-vue-i18n-generator
jwerd/inertia-table
siberfx/flysystem-wasabi
hollyit/token-replace
ippanelcom/laravel-sdk
adachsoft/changelog-linter
adachsoft/collection
payerurl/telegrambot-crypto-payment-instant-payout
dskripchenko/laravel-hybrid-search
riorizkyrainey/lara-ced
mehedimi/static-vel
zharp/zharp
nonsapiens/bigquery-model-sync
lgu-bayambang-ict-office/lgu-laravel-development-standards
andydefer/laravel-support
se7enxweb/flysystem
lampwick/laravel
jeslage/statamic-emojis
micahdshackelford/rmap-laravel