在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安全頭,提高網站的安全性。