nginx结合php使用FastCGI方式
apache结合php,php是作为一个模块加载到apache中
(1)FastCGI工作原理
1.用户发送http请求报文给nginx服务器
2.nginx会根据文件url和后缀来判断请求
3.如果请求的是静态内容,nginx会将结果直接返回给⽤户
4.如果请求的是动态内容,nginx会将请求交给fastcgi客户端,通过fastcgi_pass将这个请求发送给php-fpm
5.php-fpm收到请求后会通过本地监听的socket交给wrapper
6.wrapper收到请求会生成新的线程调用php动态程序解析服务器
7.如果用户请求的是博文、或者内容、 PHP会请求MySQL查询结果
8.php会将查询到的结果交给Nginx
10.nginx会生成一个响应报文返还给用户
php-fpm负责接收请求,/etc/php.ini
wrapper生成子进程解析用户的请求(php文件),配置文件/etc/php-fpm.conf /etc/php-fpm.d
(2)php-ini优化
#vim /etc/php.ini
sql.safe_mode = Off //打开php的安全模式,控制php执⾏危险函数, 默认是Off,改为On
expose_php = On //关闭php头部信息, 隐藏版本号, 默认是On,该为Off
display_error = Off //记录错误日志至后台,方便追溯
error_reporting = E_WARNING & E_ERROR
memory_limit = 128M //每个脚本时间最大内存
upload_max_filesize = 2M //上传文件最大许可,默认2M,建议调整为16,32M
allow_url_fopen = On //禁止远程执行phpshell,默认On,建议Off
date.timezone = PRC //时区调整,默认PRC, 建议调整为Asia/Shanghai
优化后的配置文件详情
sql.safe_mode = Off
expose_php = Off
display_error = Off
error_reporting = E_WARNING & E_ERROR
log_errors = On
error_log = /var/log/php_error.log
upload_max_filesize = 50M
allow_url_fopen = Off
date.timezone = Asia/Shanghai
(3)php-fpm优化
1.php-fpm生产环境配置文件,适合4核16G和8核16G
# cat /etc/php-fpm.d/www.conf
[global]
pid = /var/run/php-fpm.pid
error_log = /var/log/php/php-fpm.log
log_level = warning
rlimit_files = 655350
events.mechanism = epoll
[www]
user = nginx
group = nginx
listen = 127.0.0.1:9000
listen.owner = www
listen.group = www
listen.mode = 0660
listen.allowed_clients = 127.0.0.1
pm = dynamic
pm.max_children = 512
pm.start_servers = 10
pm.min_spare_servers = 10
pm.max_spare_servers = 30
pm.process_idle_timeout = 15s;
pm.max_requests = 2048
php_flag[display_errors] = off
php_admin_value[error_log] = /var/log/php/php-www.log
php_admin_flag[log_errors] = on
request_slowlog_timeout = 5s
slowlog = /var/log/php/php-slow.log
2.php-fpm配置详解
[global]
pid = /var/run/php-fpm.pid //pid设置, 记录程序启动后pid
error_log = /var/log/php/php-fpm.log //php-fpm程序启动错误日志路径
log_level = warning //错误级别,默认: notice.
rlimit_files = 655350 //文件打开描述符的rlimit限制
events.mechanism = epoll //epoll模型
[www]
user = nginx //启动进程的用户和组
group = nginx
listen = 127.0.0.1:9000 //fpm监听端口
listen.owner = www
listen.group = www
listen.mode = 0660
listen.allowed_clients = 127.0.0.1 //允许访问FastCGI进程的IP,any不限制
pm = dynamic //pm设置动态调度
pm.max_children = 512 //同一时刻最大的php-fpm子进程数量
pm.start_servers = 10 //动态方式下的起始php-fpm进程数量
pm.min_spare_servers = 10 //动态方式下服务器 空闲时最小php-fpm进程数量
pm.max_spare_servers = 30 //动态 方式下服务器 空闲时最大php-fpm进程数量
pm.process_idle_timeout = 15s; //空闲超时时间
pm.max_requests = 2048 //最大请求
php_flag[display_errors] = off //FPM状态页面,用于监控php-fpm状态使用
php_admin_value[error_log] = /var/log/php/php-www.log
php_admin_flag[log_errors] = on
request_slowlog_timeout = 5s //配置php慢查询,以及慢查询记录日志位置
slowlog = /var/log/php/php-slow.log