0
0
NginxHow-ToBeginner · 3 min read

How to Configure X-Frame-Options in Nginx for Security

To configure X-Frame-Options in Nginx, add the header directive add_header X-Frame-Options "SAMEORIGIN"; inside your server or location block. This header controls if your site can be embedded in frames, helping prevent clickjacking.
📐

Syntax

The X-Frame-Options header is set using the add_header directive in Nginx. It has three main values:

  • DENY: Prevents any domain from framing the content.
  • SAMEORIGIN: Allows framing only from the same origin.
  • ALLOW-FROM uri: Allows framing only from the specified uri (less supported).

Example syntax:

add_header X-Frame-Options "SAMEORIGIN";
nginx
add_header X-Frame-Options "SAMEORIGIN";
💻

Example

This example shows how to add the X-Frame-Options header inside an Nginx server block to allow framing only from the same origin.

nginx
server {
    listen 80;
    server_name example.com;

    location / {
        root /var/www/html;
        index index.html;

        add_header X-Frame-Options "SAMEORIGIN";
    }
}
Output
When a browser requests a page from this server, the HTTP response will include the header: X-Frame-Options: SAMEORIGIN This instructs browsers to only allow the page to be framed by pages from the same domain.
⚠️

Common Pitfalls

Common mistakes when configuring X-Frame-Options in Nginx include:

  • Placing add_header outside the server or location blocks where it has no effect.
  • Using ALLOW-FROM which is not supported by all browsers.
  • Not restarting or reloading Nginx after changes, so the header is not applied.
  • Overriding headers unintentionally by multiple add_header directives without always parameter.

Correct usage example with always to ensure header is set on all responses:

nginx
add_header X-Frame-Options "DENY" always;
📊

Quick Reference

ValueMeaningBrowser Support
DENYDisallow all framingAll modern browsers
SAMEORIGINAllow framing from same origin onlyAll modern browsers
ALLOW-FROM uriAllow framing from specified URI (limited support)Not supported by Chrome, Edge, Firefox

Key Takeaways

Use add_header X-Frame-Options "SAMEORIGIN"; inside server or location blocks to set the header.
Prefer SAMEORIGIN or DENY values for broad browser support.
Reload Nginx after configuration changes to apply the header.
Avoid ALLOW-FROM due to poor browser support.
Use the always parameter with add_header to ensure headers are sent on all responses.