ubuntu

PHP在Ubuntu上的最佳配置

小樊
44
2025-05-09 22:26:58
栏目: 编程语言

在Ubuntu上配置PHP环境是一个相对简单的过程,以下是一个详细的步骤指南,包括安装、配置、性能优化和安全设置。

安装PHP及其扩展

  1. 更新系统包
sudo apt update
  1. 安装PHP及其基本扩展
sudo apt install php php-cli php-fpm php-mysql php-zip php-gd php-mbstring php-curl php-xml php-bcmath
  1. 验证PHP安装
php -v

配置Web服务器

使用Apache

  1. 安装Apache
sudo apt install apache2
  1. 启用PHP模块
sudo a2enmod php7.4-fpm  # 替换为你的PHP版本
  1. 重启Apache
sudo systemctl restart apache2
  1. 配置Apache与PHP集成: 确保在/etc/apache2/sites-available/目录下有一个配置文件,例如000-default.conf,并包含以下内容:
<VirtualHost *:80>
    ServerName localhost
    DocumentRoot /var/www/html
    <Directory /var/www/html>
        Options Indexes FollowSymLinks
        AllowOverride All
        Require all granted
    </Directory>
</VirtualHost>
  1. 启用Apache重写模块
sudo a2enmod rewrite
  1. 重启Apache
sudo systemctl restart apache2

使用Nginx

  1. 安装Nginx
sudo apt install nginx
  1. 配置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;
    }
}
  1. 重启Nginx
sudo systemctl restart nginx

性能优化

  1. 启用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
  1. 调整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
  1. 重启PHP-FPM和Nginx
sudo systemctl restart php7.4-fpm
sudo systemctl restart nginx

安全设置

  1. 编辑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 /var/www/html:/tmp
allow_url_fopen Off
allow_url_include Off
  1. 配置防火墙: 使用UFW配置防火墙规则:
sudo ufw allow 22/tcp  # 允许SSH
sudo ufw allow 80/tcp  # 允许HTTP
sudo ufw allow 443/tcp # 允许HTTPS
sudo ufw enable
  1. 定期更新系统和软件包: 保持系统和软件包的最新状态,以修复已知的安全漏洞:
sudo apt update
sudo apt upgrade

通过以上步骤,你可以在Ubuntu上成功配置PHP环境,并进行性能优化和安全设置。请根据你的具体需求调整配置。

0
看了该问题的人还看了