PHPackages                             philiprehberger/laravel-security-headers - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Security](/categories/security)
4. /
5. philiprehberger/laravel-security-headers

ActiveLibrary[Security](/categories/security)

philiprehberger/laravel-security-headers
========================================

Laravel middleware for comprehensive security headers including CSP with nonce support, HSTS, and Permissions-Policy

v1.1.5(1mo ago)116[1 PRs](https://github.com/philiprehberger/laravel-security-headers/pulls)MITPHPPHP ^8.2CI passing

Since Mar 6Pushed 1mo agoCompare

[ Source](https://github.com/philiprehberger/laravel-security-headers)[ Packagist](https://packagist.org/packages/philiprehberger/laravel-security-headers)[ Docs](https://github.com/philiprehberger/laravel-security-headers)[ RSS](/packages/philiprehberger-laravel-security-headers/feed)WikiDiscussions main Synced 1mo ago

READMEChangelogDependencies (8)Versions (8)Used By (0)

Laravel Security Headers
========================

[](#laravel-security-headers)

[![Tests](https://github.com/philiprehberger/laravel-security-headers/actions/workflows/tests.yml/badge.svg)](https://github.com/philiprehberger/laravel-security-headers/actions/workflows/tests.yml)[![Latest Version on Packagist](https://camo.githubusercontent.com/afd2f3645d343f142dadfb8aca7f31632a70dc1a9e5cb73e243f0fd55b3328ba/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f7068696c69707265686265726765722f6c61726176656c2d73656375726974792d686561646572732e737667)](https://packagist.org/packages/philiprehberger/laravel-security-headers)[![License](https://camo.githubusercontent.com/9a8aebfdbdfdf336715c41680639d69377c563437e8899bf234a691278079dfa/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f6c6963656e73652f7068696c69707265686265726765722f6c61726176656c2d73656375726974792d68656164657273)](LICENSE)

Laravel middleware for comprehensive security headers including CSP with nonce support, HSTS, and Permissions-Policy.

Requirements
------------

[](#requirements)

- PHP 8.2+
- Laravel 11 or 12

### Features

[](#features)

- Per-request CSP nonce — generated automatically and shared with all Blade views
- Content Security Policy built entirely from config arrays, no code changes required
- Configurable HSTS with `max_age` and `includeSubDomains`
- `X-Content-Type-Options`, `X-Frame-Options`, `X-XSS-Protection`, `Referrer-Policy`, `Permissions-Policy`
- Vite dev-server auto-detection adds the HMR origin and WebSocket URLs to the CSP when `APP_ENV=local`
- Any header can be suppressed by setting its config value to `null`
- Laravel 11 and 12 support, PHP 8.2+

Installation
------------

[](#installation)

```
composer require philiprehberger/laravel-security-headers
```

Laravel auto-discovery registers the service provider automatically.

Usage
-----

[](#usage)

### Publishing the Config

[](#publishing-the-config)

```
php artisan vendor:publish --tag=security-headers-config
```

This copies `config/security-headers.php` into your application's `config/` directory.

### Registering the Middleware

[](#registering-the-middleware)

#### Laravel 11+ (bootstrap/app.php)

[](#laravel-11-bootstrapappphp)

```
use PhilipRehberger\SecurityHeaders\SecurityHeaders;

->withMiddleware(function (Middleware $middleware) {
    $middleware->web(append: [
        SecurityHeaders::class,
    ]);
})
```

#### Laravel 10 and earlier (app/Http/Kernel.php)

[](#laravel-10-and-earlier-apphttpkernelphp)

```
protected $middlewareGroups = [
    'web' => [
        // ...
        \PhilipRehberger\SecurityHeaders\SecurityHeaders::class,
    ],
];
```

### Using the CSP Nonce in Blade

[](#using-the-csp-nonce-in-blade)

The nonce is shared to every view under the variable name configured in `csp.nonce_view_variable` (default: `cspNonce`).

```

    console.log('Inline script allowed by CSP nonce');

    /* Inline styles allowed by CSP nonce */

```

#### Accessing the Nonce in PHP

[](#accessing-the-nonce-in-php)

```
$nonce = $request->attributes->get('csp_nonce');
```

### Configuration Reference

[](#configuration-reference)

```
// config/security-headers.php

return [

    'hsts' => [
        // Set SECURITY_HEADERS_HSTS=true in .env (only when fully on HTTPS)
        'enabled'            => env('SECURITY_HEADERS_HSTS', false),
        'max_age'            => 31536000,
        'include_subdomains' => true,
    ],

    'csp' => [
        'enabled'                 => true,
        'nonce_view_variable'     => 'cspNonce',
        'nonce_request_attribute' => 'csp_nonce',

        'unsafe_eval'  => true,   // include 'unsafe-eval' in script-src
        'unsafe_inline' => true,  // include 'unsafe-inline' in style-src

        // Extra sources merged into each directive
        'script_src'   => [],   // appended to: 'self' 'nonce-...' (+ 'unsafe-eval' if enabled)
        'style_src'    => [],   // appended to: 'self' (+ 'unsafe-inline' if enabled)
        'img_src'      => [],   // appended to: 'self' data: blob:
        'font_src'     => [],   // appended to: 'self' data:
        'connect_src'  => [],   // appended to: 'self'
        'frame_ancestors' => ["'self'"],
        'form_action'     => ["'self'"],
    ],

    // Set to null to omit the header entirely
    'x_content_type_options' => 'nosniff',
    'x_frame_options'        => 'SAMEORIGIN',
    'x_xss_protection'       => '1; mode=block',
    'referrer_policy'        => 'strict-origin-when-cross-origin',
    'permissions_policy'     => 'geolocation=(), camera=(), microphone=(), payment=()',

    'vite' => [
        'enabled'    => true,
        'dev_server' => 'http://127.0.0.1:5173',
    ],

];
```

### Hardening the CSP

[](#hardening-the-csp)

By default, `'unsafe-eval'` is included in `script-src` and `'unsafe-inline'` is included in `style-src` for broad compatibility. You can disable these for stricter security:

```
'csp' => [
    'unsafe_eval'   => false,  // removes 'unsafe-eval' from script-src
    'unsafe_inline' => false,  // removes 'unsafe-inline' from style-src
],
```

When `unsafe_inline` is disabled, all inline styles must use the CSP nonce. When `unsafe_eval` is disabled, `eval()` and related JavaScript features are blocked.

#### Hardcoded CSP Directives

[](#hardcoded-csp-directives)

The following directives are always included and cannot be changed via config:

DirectiveValuePurpose`default-src``'self'`Fallback for all resource types`base-uri``'self'`Prevents `` tag hijacking`object-src``'none'`Blocks Flash/Java embeds### Customization Examples

[](#customization-examples)

#### Allow an external CDN for scripts

[](#allow-an-external-cdn-for-scripts)

```
'csp' => [
    'script_src' => ['https://cdn.jsdelivr.net'],
],
```

#### Allow external font providers

[](#allow-external-font-providers)

```
'csp' => [
    'font_src'  => ['https://fonts.bunny.net', 'https://fonts.gstatic.com'],
    'style_src' => ['https://fonts.bunny.net'],
],
```

#### Allow WebSocket connections to a production server

[](#allow-websocket-connections-to-a-production-server)

```
'csp' => [
    'connect_src' => ['wss://ws.example.com'],
],
```

#### Allow forms to post to a subdomain

[](#allow-forms-to-post-to-a-subdomain)

```
'csp' => [
    'form_action' => ["'self'", 'https://portal.example.com'],
],
```

#### Enable HSTS in production via environment variable

[](#enable-hsts-in-production-via-environment-variable)

```
SECURITY_HEADERS_HSTS=true
```

#### Remove a header you do not need

[](#remove-a-header-you-do-not-need)

```
'x_xss_protection' => null,
```

API
---

[](#api)

### Middleware

[](#middleware)

ClassDescription`SecurityHeaders`Middleware that injects all configured security headers into each response and generates a per-request CSP nonce### Service Provider

[](#service-provider)

Auto-discovered via Laravel's package discovery. Registers the middleware and publishes the config file.

### Blade Variable

[](#blade-variable)

VariableDescription`$cspNonce`Per-request CSP nonce shared to all Blade views (name configurable via `csp.nonce_view_variable`)### Request Attribute

[](#request-attribute)

AttributeDescription`csp_nonce`Per-request CSP nonce accessible via `$request->attributes->get('csp_nonce')`Development
-----------

[](#development)

```
composer install
vendor/bin/phpunit
vendor/bin/pint --test
vendor/bin/phpstan analyse
```

License
-------

[](#license)

MIT

###  Health Score

41

—

FairBetter than 89% of packages

Maintenance89

Actively maintained with recent releases

Popularity10

Limited adoption so far

Community6

Small or concentrated contributor base

Maturity51

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~2 days

Total

7

Last Release

53d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/cfd7d24cbbf32400fa13ce0bbe7a31edd2d66a6d4488eafdb3d64c5337bf0435?d=identicon)[philiprehberger](/maintainers/philiprehberger)

---

Top Contributors

[![philiprehberger](https://avatars.githubusercontent.com/u/8218077?v=4)](https://github.com/philiprehberger "philiprehberger (14 commits)")

---

Tags

middlewarelaravelsecurityheaderscsphsts

###  Code Quality

TestsPHPUnit

Static AnalysisPHPStan

Code StyleLaravel Pint

### Embed Badge

![Health badge](/badges/philiprehberger-laravel-security-headers/health.svg)

```
[![Health](https://phpackages.com/badges/philiprehberger-laravel-security-headers/health.svg)](https://phpackages.com/packages/philiprehberger-laravel-security-headers)
```

###  Alternatives

[spatie/laravel-csp

Add CSP headers to the responses of a Laravel app

8519.6M19](/packages/spatie-laravel-csp)[mazedlx/laravel-feature-policy

Add Feature-Policy headers to the responses of a Laravel app

17180.5k](/packages/mazedlx-laravel-feature-policy)[stevenmaguire/laravel-middleware-csp

Provides support for enforcing Content Security Policy with headers in Laravel responses.

39107.6k](/packages/stevenmaguire-laravel-middleware-csp)[laragear/poke

Keep your forms alive, avoid TokenMismatchException by gently poking your Laravel app

2211.5k](/packages/laragear-poke)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
