在Ubuntu上配置PHP安全头可以通过修改PHP的配置文件来实现。以下是一些常见的安全头及其配置方法:
.htaccess
文件如果你使用的是Apache服务器,可以在网站的根目录下创建或编辑 .htaccess
文件,并添加以下内容:
<IfModule mod_headers.c>
Header always set X-Content-Type-Options "nosniff"
Header always set X-Frame-Options "SAMEORIGIN"
Header always set X-XSS-Protection "1; mode=block"
Header always set Content-Security-Policy "default-src 'self'; script-src 'self' https://trustedscripts.example.com; object-src 'none'"
Header always set Referrer-Policy "no-referrer-when-downgrade"
Header always set Feature-Policy "accelerometer 'none'; camera 'none'; geolocation 'none'; microphone 'none';"
</IfModule>
php.ini
文件如果你使用的是PHP-FPM或CLI模式,可以编辑 php.ini
文件。找到并修改以下配置:
[http_header]
x_content_type_options = "nosniff"
x_frame_options = "SAMEORIGIN"
x_xss_protection = "1; mode=block"
然后重启PHP-FPM服务:
sudo systemctl restart php-fpm
nginx
配置如果你使用的是Nginx服务器,可以在网站的配置文件中添加以下内容:
server {
listen 80;
server_name example.com;
location / {
add_header X-Content-Type-Options "nosniff";
add_header X-Frame-Options "SAMEORIGIN";
add_header X-XSS-Protection "1; mode=block";
add_header Content-Security-Policy "default-src 'self'; script-src 'self' https://trustedscripts.example.com; object-src 'none'";
add_header Referrer-Policy "no-referrer-when-downgrade";
add_header Feature-Policy "accelerometer 'none'; camera 'none'; geolocation 'none'; microphone 'none';";
root /var/www/html;
index index.php index.html index.htm;
}
location ~ \.php$ {
include snippets/fastcgi-php.conf;
fastcgi_pass unix:/var/run/php/php7.4-fpm.sock;
}
}
然后重启Nginx服务:
sudo systemctl restart nginx
mod_security
如果你希望更高级的安全控制,可以考虑使用 mod_security
。首先安装 mod_security
:
sudo apt-get install libapache2-mod-security2
然后启用 mod_security
:
sudo a2enmod security2
创建或编辑 /etc/modsecurity/modsecurity.conf
文件,添加你的安全规则。
最后重启Apache服务:
sudo systemctl restart apache2
通过以上方法,你可以在Ubuntu上配置PHP安全头,提高网站的安全性。