Mac下 配置nginx和PHP通信
背景
…
原理
nginx 是一个高性能的http服务器和反向代理服务器。即nginx可以作为一个HTTP服务器进行网站的发布处理,也可以作为一个反向代理服务器进行负载均衡。
但是:nginx本身并不会对php文件进行解析。对PHP页面的请求将会被nginx交给FastCGI进程监听的IP地址及端口,由php-fpm(第三方的fastcgi进程管理器)作为动态解析服务器处理,最后将处理结果再返回给nginx。即nginx通过反向代理功能将动态请求转向后端php-fpm,从而实现对PHP的解析支持,这就是Nginx实现PHP动态解析的基本原理。
实现思路
Nginx的PHP FastCGI模块允许nginx同FastCGI协同工作,因此通过nginx.conf文件的配置实现nginx实现php动态解析。
具体操作
#启动PHP
php-fpm
#启动nginx
nginx
#通过chrome浏览器的HostAdmin App插件设置Host
127.0.0.1 local.wukongbangfu.com
补充说明:
如遇到无权限操作问题,执行以下命令即可:sudo chmod og+w /etc/hosts
新建虚拟机配置文件wukongbangfu.conf
server {
listen 8088;
server_name local.wukongbangfu.com;
#charset koi8-r;
#access_log logs/host.access.log main;
root path/php/wukongbangfu/public/;
# location / {
# root html;
# index index.html index.htm;
# }
#error_page 404 /404.html;
location ~ \.php$ {
index index.php;
fastcgi_pass 127.0.0.1:9000;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
include fastcgi_params;
}
# deny access to .htaccess files, if Apache's document root
# concurs with nginx's one
#
#location ~ /\.ht {
# deny all;
#}
}
#重启nginx
nginx -s reload
#在虚拟机目录下新建index.php测试文件
<?php
phpinfo();
#打开浏览器输入localhost:8088/index.php,查看效果
显然,访问结果不符合预期!
上述问题解决,参考此文:
Primary script unknown“ while reading response header from upstream 问题修复
常见问题
启动nginx报错nginx: [emerg] open() “xxx logs/error.log” failed (2: No such file or directory)
问题现象
(base) ➜ nginx sudo nginx nginx: [emerg] open()
“/usr/local/Cellar/nginx/1.19.1/logs/error.log” failed (2: No such
file or directory)
错误分析
进入目录/usr/local/Cellar/nginx/1.19.1/发现缺少logs文件夹,因此在此目录下新建logs文件夹,重新执行nginx启动命令(nginx
sudo nginx),可正常运行。
Nginx报错403 forbidden (13: Permission denied)
问题现象
2020/07/17 19:39:09 [error] 99381#0: *165
“/Users/apple/Documents/Mac/C-repository/local/php/wukongbangfu/index.html”
is forbidden (13: Permission denied), client: 127.0.0.1, server:
localhost, request: “GET / HTTP/1.1”, host: “localhost:8080”
错误分析
文件缺少访问权限,因此给予文件可执行权限:chmod -R 755 file;重新访问链接地址,发现可正常访问。