# How to set Content-Security-Policy on Apache

> Add a Content-Security-Policy header in Apache with mod_headers, keep it on error pages and redirects, test it in report-only mode and avoid duplicates. Tested configs.

Author: Joshua Martinelle, Security engineer at Tenable (https://www.websec0.com/guides/authors/joshua-martinelle/)
Canonical: https://www.websec0.com/guides/content-security-policy/apache/
Updated: 2026-10-18
Tested on: Apache httpd 2.4.58, 2.4.62 and 2.4.69

## In short

- Set the policy with `Header always set Content-Security-Policy "…"` in the `VirtualHost`, with `mod_headers` enabled. Without `always`, 404 pages and redirects are sent without it.
- Unlike Nginx, a `<Location>` or `<Directory>` that sets another header keeps the virtual host's CSP. Setting the CSP again in a section replaces it for that path.
- Behind `mod_proxy_http`, `Header always set` adds a second policy next to the application's. Put `Header unset Content-Security-Policy` before it to keep one.
- Start with `Content-Security-Policy-Report-Only` and a `Reporting-Endpoints` header, then rename the header once violations stop.
- Apache has no nonce generator. Use hashes on static sites, or let your application generate nonces.

## The short answer

Add this line to the `VirtualHost` of your site, check the configuration and
reload Apache:

```apache
<VirtualHost *:443>
    ServerName example.com
    DocumentRoot "/var/www/example"
    SSLEngine on
    SSLCertificateFile    /etc/ssl/example.com/fullchain.pem
    SSLCertificateKeyFile /etc/ssl/example.com/privkey.pem

    Header always set Content-Security-Policy "default-src 'self'; script-src 'self'; style-src 'self'; img-src 'self' data:; font-src 'self'; connect-src 'self'; object-src 'none'; base-uri 'self'; form-action 'self'; frame-ancestors 'none'; upgrade-insecure-requests"
</VirtualHost>
```

```sh
sudo apachectl configtest && sudo apachectl graceful
```

The word `always` keeps the header on error pages and redirects. Every
snippet below was run on Apache httpd 2.4.58, 2.4.62 and 2.4.69 and checked
with `curl`, on a page, a 404 and a proxied application.

If you have not chosen a policy yet, read
[what each CSP directive does](/guides/content-security-policy/) first. The
policy above suits a site that loads everything from its own domain and has no
inline scripts.

## Before you start

The `Header` directive comes from `mod_headers`. Check that it is loaded:

```sh
apachectl -M | grep headers
```

It should print `headers_module`. On Debian and Ubuntu, enable it with
`sudo a2enmod headers`; elsewhere, uncomment its `LoadModule` line in
`httpd.conf`.

Then find where your site is defined and any existing `Header` lines:

```sh
apachectl -S
grep -rn "Header" /etc/apache2/ /etc/httpd/ 2>/dev/null
```

Wrap the whole policy in double quotes and keep the single quotes around
keywords like `'self'` and `'none'`.

## Step 1: ship the policy in report-only mode

Report-only mode applies the policy without blocking anything. Pair it with a
`Reporting-Endpoints` header so violations from real visitors reach you:

```apache
<VirtualHost *:443>
    # ...
    Header always set Reporting-Endpoints "csp-endpoint=\"https://example.com/csp-reports\""
    Header always set Content-Security-Policy-Report-Only "default-src 'self'; script-src 'self'; style-src 'self'; img-src 'self' data:; font-src 'self'; connect-src 'self'; object-src 'none'; base-uri 'self'; form-action 'self'; frame-ancestors 'none'; report-to csp-endpoint; report-uri https://example.com/csp-reports"
</VirtualHost>
```

The `Reporting-Endpoints` value contains double quotes, so escape them with a
backslash. Wrapping the value in single quotes instead also works:
`'csp-endpoint="https://example.com/csp-reports"'`. Our test returned
`Reporting-Endpoints: csp-endpoint="https://example.com/csp-reports"` either
way.

`report-to` sends reports through the Reporting API. Keep `report-uri` as a
fallback for older browsers. The endpoint must use HTTPS. Browse your main
pages with the developer console open, fix what is reported, and let real
traffic run against the policy for a few days.

## Step 2: keep it on error pages and redirects

Apache stores response headers in two tables. `Header set` writes to the one
used for successful responses; `Header always set` writes to the one that is
also sent on errors and redirects. Our test with
`Header set Content-Security-Policy "default-src 'self'"`:

```http
HTTP/1.1 200 OK
Content-Security-Policy: default-src 'self'

HTTP/1.1 404 Not Found
(no Content-Security-Policy header)

HTTP/1.1 301 Moved Permanently
(no Content-Security-Policy header)
```

With `Header always set`, all three responses carried the policy. Use
`always` for every security header.

## Step 3: where to put it

A `Header` line in the `VirtualHost` applies to the whole site. Apache merges
`<Directory>`, `<Files>` and `<Location>` sections on top of it, in that
order, and `.htaccess` files with the `<Directory>` sections. This differs
from Nginx in a useful way: a section that sets **another** header keeps the
CSP.

```apache
<VirtualHost *:443>
    # ...
    Header always set Content-Security-Policy "default-src 'self'; script-src 'self'; style-src 'self'; img-src 'self' data:; font-src 'self'; connect-src 'self'; object-src 'none'; base-uri 'self'; form-action 'self'; frame-ancestors 'none'; upgrade-insecure-requests"

    <Location "/assets/">
        # The CSP above is still sent for /assets/.
        Header always set Cache-Control "public, max-age=31536000, immutable"
    </Location>
</VirtualHost>
```

Our test returned both headers for `/assets/app.js`.

To give one path a different policy, set the CSP again in a section. The
later `set` replaces the earlier one:

```apache
<Location "/embed/">
    Header always set Content-Security-Policy "default-src 'self'; frame-ancestors 'self' https://partner.example"
</Location>
```

Our test returned only the `/embed/` policy for `/embed/` and for a 404
under it, and the site-wide policy everywhere else.

On shared hosting without access to the virtual host, the same line works in
`.htaccess`, provided the directory allows it with `AllowOverride FileInfo`:

```apache
# .htaccess
<IfModule mod_headers.c>
    Header always set Content-Security-Policy "default-src 'self'; object-src 'none'; base-uri 'self'; frame-ancestors 'none'"
</IfModule>
```

Apache reads `.htaccess` files on every request; prefer the virtual host
when you can.

## Step 4: enforce the policy

When the reports have gone quiet, rename the header from
`Content-Security-Policy-Report-Only` to `Content-Security-Policy`. Keep the
reporting directives: they now report blocked resources.

```apache
Header always set Content-Security-Policy "default-src 'self'; script-src 'self'; style-src 'self'; img-src 'self' data:; font-src 'self'; connect-src 'self'; object-src 'none'; base-uri 'self'; form-action 'self'; frame-ancestors 'none'; upgrade-insecure-requests; report-to csp-endpoint; report-uri https://example.com/csp-reports"
```

To tighten the policy later, add a stricter candidate as a second,
report-only header next to the enforced one.

## Hashes and nonces

A static site cannot use nonces, because the same HTML is served to everyone.
List the hash of each inline script instead. The hash covers the exact text
between `<script>` and `</script>`, whitespace included:

```sh
printf '%s' "console.log('ok')" | openssl sha256 -binary | openssl base64
# z45zR03J8fjhB+XZI75tfFNuEulXqY6Qn0ZMYwFwVws=
```

```apache
Header always set Content-Security-Policy "script-src 'self' 'sha256-z45zR03J8fjhB+XZI75tfFNuEulXqY6Qn0ZMYwFwVws='; object-src 'none'; base-uri 'self'; frame-ancestors 'none'"
```

Apache has no built-in way to generate a nonce and insert it into the page.
For a dynamic site, let the application generate a fresh nonce for each
response, write it into the HTML, and send the header itself. Then make sure
Apache does not add a second policy (next step).

## Behind a reverse proxy or PHP

When Apache sits in front of an application that sends its own CSP, the
result depends on how the application is connected. Apache's documentation
explains that headers from CGI scripts and `mod_proxy_fcgi`, which runs PHP-FPM,
land in the `always` table, while `mod_proxy_http` puts the backend's headers
in the default one.

With `mod_proxy_http` and `Header always set`, our test returned two policies:

```http
HTTP/1.1 200 OK
Content-Security-Policy: default-src 'self'
Content-Security-Policy: default-src *
```

Browsers enforce both, so the stricter combination applies and pages break in
confusing ways. With a CGI application, the opposite happened: `Header always
set` replaced the application's policy, and `Header set` produced two.

One pattern handles both cases. Remove the header from the default table,
then set it in the `always` table:

```apache
<VirtualHost *:443>
    # ...
    ProxyPass "/" "http://127.0.0.1:8080/"
    Header unset Content-Security-Policy
    Header always set Content-Security-Policy "default-src 'self'; object-src 'none'; base-uri 'self'; frame-ancestors 'none'"
</VirtualHost>
```

Our test returned a single policy, Apache's, for the proxied application, for
its 404 pages and for the CGI application. If the application owns the
policy, for example because it generates nonces, remove both lines instead.

## Only on HTML responses

The policy only matters on documents. To skip it on images, scripts and
stylesheets, add a condition on the response type:

```apache
Header always set Content-Security-Policy "default-src 'self'; object-src 'none'; base-uri 'self'; frame-ancestors 'none'" "expr=%{CONTENT_TYPE} =~ m#^text/html#"
```

Our test sent the header on the home page and on the HTML 404 page, but not
on `app.js`. Sending it everywhere is harmless, so this is optional.

## Verify it

Check the header on a normal page, an error page and a redirect:

```sh
curl -sI https://example.com/ | grep -i content-security-policy
curl -sI https://example.com/does-not-exist | grep -i content-security-policy
curl -sI http://example.com/ | grep -iE "^location|content-security-policy"
```

Count the headers to catch duplicates. The result should be `1`:

```sh
curl -sI https://example.com/ | grep -ci '^content-security-policy:'
```

Then scan the site with WebSec0. The headers report shows the policy it
received and whether it passes.

## Troubleshooting

| Symptom | Likely cause | Fix |
| --- | --- | --- |
| `Invalid command 'Header'` | `mod_headers` is not loaded | `a2enmod headers`, or uncomment its `LoadModule` line. |
| Header missing on 404 pages or redirects | `Header set` without `always` | Write `Header always set`. |
| Two `Content-Security-Policy` headers | A proxied application sends one too | Add `Header unset Content-Security-Policy` before `Header always set`. |
| `.htaccess` line ignored, or a 500 error with `Header not allowed here` in the error log | `AllowOverride` is `None`, or does not include `FileInfo` | Allow `FileInfo` for that directory, or move the line to the virtual host. |
| Policy different on some paths | A `<Location>`, `<Directory>` or `.htaccess` sets the CSP again | Search the configuration and `.htaccess` files for `Content-Security-Policy`. |
| Inline scripts blocked after enforcing | No nonce or hash for them | Move them to files, or add hashes or application nonces. |
| Changes do not show up | Reload skipped, or a CDN cached old headers | `apachectl configtest && apachectl graceful`, then purge the CDN. |

## Frequently asked questions

### How do I add a Content-Security-Policy header in Apache?

Enable `mod_headers` and add `Header always set Content-Security-Policy "default-src 'self'; …"` to the `VirtualHost`, then run `apachectl configtest` and `apachectl graceful`.

### Why is my CSP missing on 404 pages or redirects?

`Header set` without `always` only writes to the table Apache uses for successful responses. Error pages and redirects generated by Apache use the `always` table. Write `Header always set`.

### Can I set Content-Security-Policy in .htaccess?

Yes, when the directory allows it with `AllowOverride FileInfo` (or `All`). Use the same `Header always set` line, wrapped in `<IfModule mod_headers.c>` if the module might be missing.

### Why does my response have two Content-Security-Policy headers?

The application behind Apache sends one too. With `mod_proxy_http`, its header sits in the default table and `Header always set` adds yours to the other one. Add `Header unset Content-Security-Policy` before the `Header always set` line.

### How do I use a different CSP for one path on Apache?

Set the header again inside a `<Location>` for that path. Apache merges sections after the virtual host, so the later `Header always set` replaces the policy there, error pages included.

### Can Apache generate a CSP nonce?

Not on its own. Generate the nonce in your application, which writes it into both the header and the HTML, or use hashes for the inline scripts of a static site.

## Sources

- [Apache Module mod_headers](https://httpd.apache.org/docs/2.4/mod/mod_headers.html), Apache HTTP Server Project
- [Configuration Sections: how the sections are merged](https://httpd.apache.org/docs/2.4/sections.html#merging), Apache HTTP Server Project
- [Expressions in Apache HTTP Server](https://httpd.apache.org/docs/2.4/expr.html), Apache HTTP Server Project
- [.htaccess files](https://httpd.apache.org/docs/2.4/howto/htaccess.html), Apache HTTP Server Project
- [Reporting-Endpoints header](https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Headers/Reporting-Endpoints), MDN Web Docs
- [Content Security Policy Level 3](https://www.w3.org/TR/CSP3/), W3C
