在Ubuntu上配置PHP环境是一个相对简单的过程,以下是一个详细的步骤指南,包括安装、配置、性能优化和安全设置。
安装PHP及其扩展
- 更新系统包:
sudo apt update
- 安装PHP及其基本扩展:
sudo apt install php php-cli php-fpm php-mysql php-zip php-gd php-mbstring php-curl php-xml php-bcmath
- 验证PHP安装:
php -v
配置Web服务器
使用Apache
- 安装Apache:
sudo apt install apache2
- 启用PHP模块:
sudo a2enmod php7.4-fpm # 替换为你的PHP版本
- 重启Apache:
sudo systemctl restart apache2
- 配置Apache与PHP集成:
确保在/etc/apache2/sites-available/目录下有一个配置文件,例如000-default.conf,并包含以下内容:
:80>
ServerName localhost
DocumentRoot /var/www/html
Options Indexes FollowSymLinks
AllowOverride All
Require all granted
- 启用Apache重写模块:
sudo a2enmod rewrite
- 重启Apache:
sudo systemctl restart apache2
使用Nginx
- 安装Nginx:
sudo apt install nginx
- 配置Nginx与PHP-FPM:
在/etc/nginx/sites-available/目录下创建或编辑一个配置文件,例如default,并包含以下内容:
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; # 替换为你的PHP版本
}
location ~ /\.ht {
deny all;
}
}
- 重启Nginx:
sudo systemctl restart nginx
性能优化
- 启用OPcache:
编辑/etc/php/7.4/fpm/php.ini(替换为你的PHP版本),取消以下行的注释:
zend_extension=opcache.so
opcache.enable=1
opcache.memory_consumption=64
opcache.max_accelerated_files=4000
opcache.revalidate_freq=2
- 调整PHP-FPM设置:
编辑/etc/php/7.4/fpm/pool.d/www.conf,调整以下设置:
pm.max_children = 50
pm.start_servers = 10
pm.min_spare_servers = 5
pm.max_spare_servers = 20
- 重启PHP-FPM和Nginx:
sudo systemctl restart php7.4-fpm
sudo systemctl restart nginx
安全设置
- 编辑php.ini:
- 关闭详细的错误报告:
display_errors Off
log_errors On
error_reporting E_ALL & E_NOTICE & E_DEPRECATED & E_STRICT & E_USER_NOTICE & E_USER_WARNING
- 启用安全模式:
safe_mode On
safe_mode_allowed_classes "mysqli,pdo_mysql"
- 禁用危险函数:
disable_functions exec,system,passthru,shell_exec,popen,curl,fsockopen,file_get_contents,mkdir,rmdir,rename,unlink,chmod,chown,chgrp,date,time,localtime,gmtime,isset,empty,is_array,is_object,is_resource,is_string,is_int,is_float,is_bool,is_callable,assert
- 使用
open_basedir限制PHP可以访问的系统目录:
open_basedir /var/www/html:/tmp
- 关闭
allow_url_fopen和allow_url_include:
allow_url_fopen Off
allow_url_include Off
- 配置防火墙:
使用UFW配置防火墙规则:
sudo ufw allow 22/tcp # 允许SSH
sudo ufw allow 80/tcp # 允许HTTP
sudo ufw allow 443/tcp # 允许HTTPS
sudo ufw enable
- 定期更新系统和软件包:
保持系统和软件包的最新状态,以修复已知的安全漏洞:
sudo apt update
sudo apt upgrade
通过以上步骤,你可以在Ubuntu上成功配置PHP环境,并进行性能优化和安全设置。请根据你的具体需求调整配置。