linux环境 nginx和php-fpm搭建https服务

1. 软件包下载

有网络的条件下可以使用yum(centos)或者apt(ubuntu)进行在线安装即可。当不能用在线安装时,可以去https://pkgs.org/下载离线包,不过可能会遇到依赖的问题,如果依赖过于复杂,可以考虑移步http://nginx.org/en/download.htmlhttps://www.php.net/downloads.php下载源码进行编译安装。

2. Nginx配置

在启动nginx之前需要对nginx的配置做一些改动,配置文件可以用rpm -ql nginx | grep default或者dpkg -S nginx | grep default查找,在这里把找到的路径列出来/etc/nginx/conf.d/default.conf(centos)或者/etc/nginx/sites-available/default(ubuntu);修改nignx配置文件之前需要准备好证书文件,修改的内容如下:

server {
    listen              443 ssl;
    server_name         localhost;
    ssl_certificate     /etc/nginx/cert/xx.pem;
    ssl_certificate_key /etc/nginx/cert/xx.key;
    ssl_protocols       TLSv1 TLSv1.1 TLSv1.2;
    ssl_ciphers         HIGH:!aNULL:!MD5;

    location / {
        root   /usr/share/nginx/html;
        index  index.html index.htm;
    }
}

nginx安装好之后默认是不开机自动启动,可以用systemctl指令来实现操作(centos默认是关闭了所有对外的连接端口,不要忘了配置防火墙规则哦):

systemctl status nginx # 查看nginx服务的运行状态
systemctl start nginx # 启动nginx服务
systemctl stop nginx # 关闭nginx服务
systemctl enable nginx # 开启自启nginx服务
systemctl disable nginx # 取消nginx开启自启

服务启动后,可以用浏览器访问https://localhost会出现nginx的欢迎界面,表示安装成功,该页面会由两个信息,一个是配置文件的路径,一个是 www 目录的路径。

3. php、php-fpm配置

php和php-fpm的版本必须要保持一致,安装完成之后可以用php -v和php-fpm -v查看版本。接下来想让nignx能够解析php还需要配置nignx的配置文件:

location ~ .php$ {
   root   /usr/share/nginx/html/php;
   fastcgi_pass   127.0.0.1:9000;
   fastcgi_index  index.php;
   # fastcgi_param  SCRIPT_FILENAME /scripts$fastcgi_script_name;
   fastcgi_param  SCRIPT_FILENAME $document_root$fastcgi_script_name;
   include        fastcgi_params;
}

注意其中的root不要和nignx的root一致;此外php-fpm默认的执行用户是apache,我们需要在/etc/php-fpm.d/www.conf里改成nginx用户:

listen.owner = nginx
listen.group = nginx
listen.mode = 0666

; RPM: apache Choosed to be able to access some dir as httpd
user = nginx
; RPM: Keep a group allowed to write in log dir.
group = nginx

以上配置完成后用systemctl restart php-fpm nginx重启服务,启动完成后可以用lsof查看9000端口的状况;接下来新建php环境测试文件vim /usr/share/nginx/html/php/index.php,内容如下:

<?php
  // test script for CentOS/RHEL 7+PHP 7.2+Nginx 
  phpinfo();
?>

用浏览器打开https://lcoalhost/index.php就会出现php version信息,如下图;如果出现错误File not found是因为索引的路径信息对不上导致的,解决方法是将

fastcgi_param SCRIPT_FILENAME  $document_root$fastcgi_script_name;

换成

fastcgi_param SCRIPT_FILENAME /scripts$fastcgi_script_name;

4. php程序执行权限问题

由nginx搭建的http/https服务,浏览器所访问的php资源实际上是由nginx用户去执行调用的(在/etc/nginx/nginx.conf有设置),并且php-fpm是不允许以root用户进行资源调用的(强制设置root用户会限制启动php-fpm服务);如果需要用php请求高权限资源时,可以考虑提高nginx的权限(在/etc/sudoers修改),然后再php脚本中执行命令时加上sudo即可。

参考文章:

[1] https://www.cnblogs.com/hftian/p/9469128.html
[2] https://www.cnblogs.com/ryanzheng/p/11263261.html
[3] https://blog.csdn.net/u011385445/article/details/89186972
[4] https://www.cnblogs.com/fozero/p/10968550.html
[5] https://stackoverflow.com/questions/24208139/nginx-php-fpm-file-not-found

原文地址:https://www.cnblogs.com/macrored/p/11867738.html