To set up Nginx to handle PHP-FPM security headers, follow these steps:
Install Nginx and PHP-FPM on your server if you haven't already. You can install them using your package manager or by compiling from source.
Open the Nginx configuration file, usually located in /etc/nginx/nginx.conf
or /etc/nginx/sites-available/default
depending on your distribution.
Inside the http
block, add the following lines to set up fastcgi parameters:
http {
# ... existing configurations ...
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
fastcgi_param QUERY_STRING $query_string;
fastcgi_param REQUEST_METHOD $request_method;
fastcgi_param CONTENT_TYPE $content_type;
fastcgi_param CONTENT_LENGTH $content_length;
# ... other fastcgi parameters ...
}
These parameters will pass the necessary information from Nginx to PHP-FPM.
server
block for your PHP-enabled site, add the following lines to set the security headers:location ~ \.php$ {
fastcgi_pass unix:/var/run/php/php7.4-fpm.sock; # Change the path to your PHP-FPM socket
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
# Add the security headers
add_header X-Content-Type-Options "nosniff";
add_header X-Frame-Options "SAMEORIGIN";
add_header X-XSS-Protection "1; mode=block";
include fastcgi_params;
}
Modify the fastcgi_pass
line to match the path to your PHP-FPM socket. You may also need to adjust the PHP version (e.g., php7.4-fpm.sock
) if you're using a different one.
sudo service nginx restart
or sudo systemctl restart nginx
.Once Nginx has been restarted, it will handle the PHP-FPM security headers for all PHP files served by the web server.