Beginner Fundamentals

Security Headers and Access Control

A few extra headers and access rules make your site noticeably safer. Nginx lets you add security headers and restrict access with simple directives.

Adding Security Headers

Use add_header to send protective headers with every response:

add_header X-Frame-Options "SAMEORIGIN";
add_header X-Content-Type-Options "nosniff";
add_header Referrer-Policy "no-referrer-when-downgrade";
  • X-Frame-Options SAMEORIGIN blocks your pages from being framed by other sites, preventing clickjacking.
  • X-Content-Type-Options nosniff stops browsers from guessing content types.
  • Referrer-Policy controls how much referrer information is shared.

Content Security Policy

A CSP limits where scripts and styles may load from:

add_header Content-Security-Policy "default-src 'self';";

Start strict with 'self' and loosen only as needed.

Restricting Access with allow and deny

You can limit who reaches a location by IP:

location /admin {
    allow 192.168.1.0/24;
    deny all;
}

Rules are read in order. Here only the 192.168.1.0/24 network is allowed; everyone else is denied.

Blocking Hidden Files

Prevent access to dotfiles like .git or .env:

location ~ /\. {
    deny all;
}

Apply and Test

sudo nginx -t
sudo systemctl reload nginx

These small additions raise your security baseline with almost no effort.