PHPackages                             jeffersongoncalves/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. jeffersongoncalves/laravel-security-headers

ActiveLibrary[Security](/categories/security)

jeffersongoncalves/laravel-security-headers
===========================================

This Laravel package stamps a configurable set of baseline security headers (X-Content-Type-Options, X-Frame-Options, Referrer-Policy, Permissions-Policy, Content-Security-Policy, Cross-Origin-Opener-Policy, X-Permitted-Cross-Domain-Policies and HSTS) onto your HTTP responses via a single middleware. Every header value and the full CSP directive map are driven by config, so you can tune or disable each one without touching code.

v2.0.0(1mo ago)259MITPHPPHP ^8.2CI passing

Since Jun 20Pushed 1mo ago1 watchersCompare

[ Source](https://github.com/jeffersongoncalves/laravel-security-headers)[ Packagist](https://packagist.org/packages/jeffersongoncalves/laravel-security-headers)[ Docs](https://github.com/jeffersongoncalves/laravel-security-headers)[ GitHub Sponsors](https://github.com/jeffersongoncalves)[ RSS](/packages/jeffersongoncalves-laravel-security-headers/feed)WikiDiscussions master Synced 2w ago

READMEChangelog (3)Dependencies (7)Versions (5)Used By (0)

[![Laravel Security Headers](https://raw.githubusercontent.com/jeffersongoncalves/laravel-security-headers/master/art/jeffersongoncalves-laravel-security-headers.png)](https://raw.githubusercontent.com/jeffersongoncalves/laravel-security-headers/master/art/jeffersongoncalves-laravel-security-headers.png)

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

[](#laravel-security-headers)

[![Latest Version on Packagist](https://camo.githubusercontent.com/929f00085a8dd5070afe677dc5ad2fd74ec222af97b6fb01e2af29423dd64187/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f6a6566666572736f6e676f6e63616c7665732f6c61726176656c2d73656375726974792d686561646572732e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/jeffersongoncalves/laravel-security-headers)[![GitHub Tests Action Status](https://camo.githubusercontent.com/68d8778a9d777df9be851f9d120f9eae32bf8a9effd009e3236f2bfcf9a7cc5f/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f616374696f6e732f776f726b666c6f772f7374617475732f6a6566666572736f6e676f6e63616c7665732f6c61726176656c2d73656375726974792d686561646572732f72756e2d74657374732e796d6c3f6272616e63683d6d6173746572266c6162656c3d7465737473267374796c653d666c61742d737175617265)](https://github.com/jeffersongoncalves/laravel-security-headers/actions?query=workflow%3Arun-tests+branch%3Amaster)[![GitHub Code Style Action Status](https://camo.githubusercontent.com/a66ef8c2e5828feff1f23b4641accf4c4ede73f2e0a135009a81d690507c74ef/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f616374696f6e732f776f726b666c6f772f7374617475732f6a6566666572736f6e676f6e63616c7665732f6c61726176656c2d73656375726974792d686561646572732f6669782d7068702d636f64652d7374796c652d6973737565732e796d6c3f6272616e63683d6d6173746572266c6162656c3d636f64652532307374796c65267374796c653d666c61742d737175617265)](https://github.com/jeffersongoncalves/laravel-security-headers/actions?query=workflow%3A%22Fix+PHP+code+styling%22+branch%3Amaster)[![Total Downloads](https://camo.githubusercontent.com/c4ce08a5bd48d279990807e1230c7cfc40fb2b63381de3f23c13a7ac27fe1cce/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f6a6566666572736f6e676f6e63616c7665732f6c61726176656c2d73656375726974792d686561646572732e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/jeffersongoncalves/laravel-security-headers)

This Laravel package stamps a configurable set of baseline security headers onto your HTTP responses via a single middleware. Every header value and the full Content-Security-Policy directive map are driven by `config/security-headers.php`, so you can tune or disable each one without touching code.

The headers it manages:

- `X-Content-Type-Options`
- `X-Frame-Options`
- `Referrer-Policy`
- `Permissions-Policy`
- `Content-Security-Policy`
- `Cross-Origin-Opener-Policy`
- `X-Permitted-Cross-Domain-Policies`
- `Strict-Transport-Security` (HSTS) — only over real HTTPS and never in the `local` environment

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

[](#installation)

You can install the package via composer:

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

You can publish the config file with:

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

Usage
-----

[](#usage)

The package ships a single middleware: `JeffersonGoncalves\SecurityHeaders\Middleware\SecurityHeaders`. The service provider **auto-registers a `security-headers` route-middleware alias** for you, but it does **not** apply the middleware globally — you must still attach it to a route or group. Place it as the **outermost** middleware of the group you want protected so it also stamps cached (HIT) responses produced further down the stack.

### Attach it via the registered alias

[](#attach-it-via-the-registered-alias)

The alias `security-headers` is wired up automatically, so you can use it directly on a route or group:

```
Route::middleware('security-headers')->group(function () {
    // ...
});
```

### Or apply it to the whole web group (Laravel 11+)

[](#or-apply-it-to-the-whole-web-group-laravel-11)

In `bootstrap/app.php`:

```
use Illuminate\Foundation\Configuration\Middleware;
use JeffersonGoncalves\SecurityHeaders\Middleware\SecurityHeaders;

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

### Legacy kernel (Laravel 10 style)

[](#legacy-kernel-laravel-10-style)

Add the middleware to a group in `app/Http/Kernel.php`:

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

Configuration
-------------

[](#configuration)

After publishing, `config/security-headers.php` exposes three blocks.

### Static headers

[](#static-headers)

Each entry is stamped onto every response. Set any value to `null` to **skip** that header:

```
'headers' => [
    'X-Content-Type-Options' => 'nosniff',
    'X-Frame-Options' => 'SAMEORIGIN',
    'Referrer-Policy' => 'strict-origin-when-cross-origin',
    'Permissions-Policy' => 'camera=(), microphone=(), geolocation=(), payment=(), usb=(), browsing-topics=()',
    'Cross-Origin-Opener-Policy' => 'same-origin-allow-popups',
    // Disable a header by setting it to null:
    'X-Permitted-Cross-Domain-Policies' => null,
],
```

### Customizing the Content-Security-Policy

[](#customizing-the-content-security-policy)

The CSP header is assembled from the associative `directives` map, **preserving order**. A value may be a string or an array of source expressions. A directive whose value is `null` (or an empty string) is emitted as a *valueless* directive (e.g. `upgrade-insecure-requests`). Set `csp.enabled` to `false` to drop the header entirely.

The shipped default is a **strict, first-party-only** policy — no `'unsafe-*'`, no third-party origins — so it is a genuine XSS backstop:

```
'csp' => [
    'enabled' => true,
    'directives' => [
        'default-src' => "'self'",
        'script-src' => "'self'",
        'style-src' => "'self'",
        'img-src' => "'self' data:",
        'object-src' => "'none'",
        'base-uri' => "'self'",
        'form-action' => "'self'",
        'frame-ancestors' => "'self'",
    ],
],
```

#### Nonces for inline scripts

[](#nonces-for-inline-scripts)

Rather than reaching for `'unsafe-inline'`, allow specific inline scripts with a per-request nonce. Put the `{nonce}` placeholder in a directive — the middleware substitutes it with a fresh, random per-request value:

```
'script-src' => "'self' 'nonce-{nonce}'",
```

Then emit the matching nonce in your Blade markup with the `@cspNonce` directive (or the `csp_nonce()` helper):

```

    // your trusted inline script

```

Both the header and the view receive the **same** value for that request, so the script validates while injected markup (which cannot guess the nonce) is blocked.

#### Report-only mode and violation reporting

[](#report-only-mode-and-violation-reporting)

Set `report-only` to emit `Content-Security-Policy-Report-Only` instead of the enforcing header (useful for rolling out a policy without breaking pages). `report-uri` / `report-to` are appended as CSP directives when non-null:

```
'csp' => [
    'enabled' => true,
    'report-only' => true,
    'report-uri' => 'https://example.com/csp-report', // legacy endpoint
    'report-to' => 'csp-endpoint',                    // Reporting-API group name
    // ...
],
```

#### Opt-in: GTM / gtag / Alpine.js (permissive)

[](#opt-in-gtm--gtag--alpinejs-permissive)

If you rely on inline Google Tag Manager / gtag and Alpine.js (which evaluates expressions via `new Function`, requiring `'unsafe-eval'`) and cannot adopt nonces, you can loosen the policy. **This removes the CSP's XSS protection** — pair it with output sanitization (e.g. `symfony/html-sanitizer`) for any untrusted markup you render:

```
'directives' => [
    'default-src' => "'self'",
    'script-src' => "'self' 'unsafe-inline' 'unsafe-eval' https://www.googletagmanager.com https://www.google-analytics.com https://static.cloudflareinsights.com",
    'style-src' => "'self' 'unsafe-inline'",
    'img-src' => "'self' data: https:",
    'font-src' => "'self' data:",
    'connect-src' => "'self' https://www.google-analytics.com https://*.google-analytics.com https://*.analytics.google.com https://www.googletagmanager.com https://cloudflareinsights.com",
    'frame-src' => "'self' https://www.googletagmanager.com",
    'frame-ancestors' => "'self'",
    'base-uri' => "'self'",
    'form-action' => "'self'",
    'object-src' => "'none'",
    'upgrade-insecure-requests' => null,
],
```

### HSTS

[](#hsts)

`Strict-Transport-Security` is only stamped over real HTTPS and never while the app is in an excluded environment (`['local']` by default — a cached `max-age` on a `*.test` domain is a pain to undo):

```
'hsts' => [
    'enabled' => true,
    'max-age' => 31536000,
    'include-subdomains' => true,
    'preload' => false,

    // Environments in which HSTS is never stamped (even over HTTPS).
    // Set to [] to stamp HSTS in every environment.
    'exclude_environments' => ['local'],
],
```

> **`preload` is a near-irreversible commitment.** Enabling it and submitting your domain to [hstspreload.org](https://hstspreload.org) hard-codes HTTPS-only for the apex domain **and every subdomain** into browsers shipped worldwide. Removal is slow (months) and painful. Leave it `false` unless you are certain every current and future subdomain serves valid TLS. It defaults to `false`.

#### HSTS depends on a correct `$request->secure()`

[](#hsts-depends-on-a-correct-request-secure)

HSTS is only emitted when Laravel considers the request secure (`$request->secure()`). Behind a TLS-terminating proxy or load balancer (the app receives plain HTTP on the back end), `secure()` returns `false` and HSTS will be silently skipped unless you configure trusted proxies. Make sure your `TrustProxies` middleware / `bootstrap/app.php` `trustProxies(...)` config is set so the `X-Forwarded-Proto` header is honoured — otherwise the proxy must add HSTS itself.

Testing
-------

[](#testing)

```
composer test
```

Changelog
---------

[](#changelog)

Please see [CHANGELOG](CHANGELOG.md) for more information on what has changed recently.

Contributing
------------

[](#contributing)

Please see [CONTRIBUTING](.github/CONTRIBUTING.md) for details.

Security Vulnerabilities
------------------------

[](#security-vulnerabilities)

Please review [our security policy](../../security/policy) on how to report security vulnerabilities.

Credits
-------

[](#credits)

- [Jèfferson Gonçalves](https://github.com/jeffersongoncalves)
- [All Contributors](../../contributors)

License
-------

[](#license)

The MIT License (MIT). Please see [License File](LICENSE.md) for more information.

###  Health Score

43

—

FairBetter than 89% of packages

Maintenance91

Actively maintained with recent releases

Popularity15

Limited adoption so far

Community9

Small or concentrated contributor base

Maturity49

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 88.9% 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 ~0 days

Total

3

Last Release

44d ago

Major Versions

v1.0.1 → v2.0.02026-06-21

### Community

Maintainers

![](https://avatars.githubusercontent.com/u/411493?v=4)[Jefferson Gonçalves](/maintainers/jeffersongoncalves)[@jeffersongoncalves](https://github.com/jeffersongoncalves)

---

Top Contributors

[![jeffersongoncalves](https://avatars.githubusercontent.com/u/411493?v=4)](https://github.com/jeffersongoncalves "jeffersongoncalves (8 commits)")[![dependabot[bot]](https://avatars.githubusercontent.com/in/29110?v=4)](https://github.com/dependabot[bot] "dependabot[bot] (1 commits)")

---

Tags

composercsphstsjeffersongoncalveslaravellaravel-packagemiddlewarephpsecuritysecurity-headerslaraveljeffersongoncalveslaravel-security-headers

###  Code Quality

TestsPest

Static AnalysisPHPStan

Code StyleLaravel Pint

### Embed Badge

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

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

###  Alternatives

[spatie/laravel-medialibrary

Associate files with Eloquent models

6.2k45.4M679](/packages/spatie-laravel-medialibrary)[spatie/laravel-health

Monitor the health of a Laravel application

88212.7M180](/packages/spatie-laravel-health)[spatie/laravel-csp

Add CSP headers to the responses of a Laravel app

86811.6M26](/packages/spatie-laravel-csp)[harris21/laravel-fuse

Circuit breaker for Laravel queue jobs. Protect your workers from cascading failures.

24773.9k](/packages/harris21-laravel-fuse)[defstudio/telegraph

A laravel facade to interact with Telegram Bots

817336.8k3](/packages/defstudio-telegraph)[nativephp/mobile

NativePHP for Mobile

1.1k102.1k123](/packages/nativephp-mobile)

PHPackages © 2026

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