在Ubuntu系统上配置PHP以确保其安全性是至关重要的。通过遵循本指南,您可以提高PHP应用程序的安全性,防止常见的安全漏洞,如SQL注入、跨站脚本(XSS)和会话劫持。
首先,确保您的系统包是最新的。打开终端并运行以下命令:
sudo apt update
sudo apt upgrade -y
使用apt
安装所需的PHP版本及其模块。例如,安装PHP 7.4及其常用模块:
sudo apt install php7.4 php7.4-cli php7.4-fpm php7.4-mysql php7.4-json php7.4-opcache -y
禁用不需要的PHP模块以减少潜在攻击面。例如,如果您不需要FTP模块,可以运行:
sudo a2dismod php7.4-ftp
编辑PHP配置文件(通常位于/etc/php/7.4/apache2/php.ini
或/etc/php/7.4/fpm/php.ini
),确保以下配置项已设置:
E_ALL & ~E_NOTICE & ~E_DEPRECATED & ~E_STRICT & ~E_USER_NOTICE
,以减少不必要的错误报告。error_reporting = E_ALL & ~E_NOTICE & ~E_DEPRECATED & ~E_STRICT & ~E_USER_NOTICE
display_errors = Off
log_errors = On
编辑Apache的配置文件(通常位于/etc/apache2/sites-available/000-default.conf
),确保在<VirtualHost>
块中包含以下内容:
<VirtualHost *:80>
ServerAdmin webmaster@localhost
DocumentRoot /var/www/html
<Directory /var/www/html>
Options Indexes FollowSymLinks
AllowOverride All
Require all granted
</Directory>
ErrorLog ${APACHE_LOG_DIR}/error.log
CustomLog ${APACHE_LOG_DIR}/access.log combined
</VirtualHost>
编辑Nginx的配置文件(通常位于/etc/nginx/sites-available/default
),确保在server
块中包含以下内容:
server {
listen 80 default_server;
listen [::]:80 default_server;
root /var/www/html;
index index.php index.html index.htm index.nginx-debian.html;
server_name _;
location / {
try_files $uri $uri/ =404;
}
location ~ \.php$ {
include snippets/fastcgi-php.conf;
fastcgi_pass unix:/var/run/php/php7.4-fpm.sock;
}
location ~ /\.ht {
deny all;
}
}
samesite
标志。session_start(['cookie_secure' => true, 'cookie_samesite' => 'strict', 'cookie_httponly' => true]);
session_regenerate_id(true);
定期审查PHP和Web服务器的配置,确保其符合最新的安全标准和最佳实践。
通过以上步骤,您可以显著提高Ubuntu系统上PHP应用程序的安全性。务必定期更新和维护您的系统和软件包,以保持其安全性。
辰迅云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
推荐阅读: VirtualBox虚拟机Ubuntu如何备份