在安装Nginx与PHP时都是独立安装的;Nginx占用80端口,php-fpm占用9000端口。收到请求以后,都要先通过80端口的Nginx软件。若是html的静态文件,nginx可以直接处理;但是.php为后缀的动态文件就不能处理。关联的目的就是为了解析php代码,因为Nginx只能解析静态页面。
正常情况下,Nginx不具备PHP代码的解析功能。在遇到PHP代码以后,会把其当作未知文件,自动将其下载。
关键步骤:让Nginx把.php文件转发给php-fpm
这一步该如何实现呢?这就需要我们修改nginx的配置文件:nginx.conf,修改完配置文件之后,可以让nginx识别.php文件,然后转发给php-fpm
[root@ceshi ~]# cd /usr/local/nginx
# 将nginx.conf文件中的注释和空白行删除
#(若想看原生配置文件的内容可以查看conf/nginx.conf.default)
[root@ceshi nginx]# grep -Ev '#|^$' conf/nginx.conf > conf/nginx.conf
# 接下来修改配置文件
[root@ceshi nginx]# vim conf/nginx.conf
修改配置文件内容
一个nginx.conf对应一个http,代表http请求,所以一个页面只有一个http;一个http可以包含多个server区块(默认情况下只有一个server),每个区块就是一个项目(网站)
worker_processes auto;
events {
worker_connections 1024;
}
http {
#隐藏版本号
server_processes off;
include mime.types;
default_type application/octet-stream;
sendfile on;
keepalive_timeout 65;
server {
# 监听端口
listen 80;
server_name 127.0.0.1;
# 指定项目目录
root /var/www/html;
# index代表默认首页(如果在html目录发现默认首页,直接运行)
index index.php index.html index.htm;
# 当访问错误时,返回50x.html页面给用户
error_page 500 502 503 504 /50x.html;
location = /50x.html {
}
# 添加PHP文件支持,最关键的修改
location ~\.php$ {
root /var/www/html;
fastcgi_pass 127.0.0.1:9000;
fastcgi_index index.php
# $document_root代表项目目录,表示找PHP代码到指定的目录去找
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
include fastcgi_params;
}
location ~ /\.ht {
deny all;
}
}
}
设置完成后,重载nginx并检查9000端口是否启用,否则手打请求后无法转发。
[root@ceshi nginx]# systemctl reload nginx
[root@ceshi nginx]# netstat -nltp|grep 9000
tcp 0 0 127.0.0.1:9000 0.0.0.0:* LISTEN 9220/php-fpm: master
创建一个index.php文件,检查nginx是否与php-fpm关联成功,顺便查看php的详细信息。
[root@ceshi html]# vim /var/www/html/index.php
# 编写如下内容
<?php
echo phpinfo();
?>