我在使用 nginx 时遇到了一些问题。我在 Raspberry Pi B+ (Raspbian Jessie) 上设置了 nginx,并使用 FastCGI 设置了 PHP。当我尝试使用 cURL 检索页面时,它返回 PHP 生成的 HTML。
为 fastcgi 请求提供服务的 nginx 服务器块
server {
listen 80 default_server;
listen [::]:80 ipv6only=on default_server;
# SSL configuration
#
# listen 443 ssl default_server;
# listen [::]:443 ssl default_server;
#
# Self signed certs generated by the ssl-cert package
# Don't use them in a production server!
#
# include snippets/snakeoil.conf;
root /usr/share/nginx/html;
# Add index.php to the list if you are using PHP
index index.php index.html index.htm index.nginx-debian.html;
server_name _;
location / {
# First attempt to serve request as file, then
# as directory, then fall back to displaying a 404.
try_files $uri $uri/ =404;
}
# pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
#
location ~ \.php$ {
# include snippets/fastcgi-php.conf;
include fastcgi_params;
try_files $uri =404;
fastcgi_split_path_info ^(.+\.php)(/.+)$;
#
# # With php5-cgi alone:
# fastcgi_pass 127.0.0.1:9000;
# With php5-fpm:
fastcgi_pass unix:/var/run/php5-fpm.sock;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
}
# deny access to .htaccess files, if Apache's document root
#oncurs with nginx's one
#
#location ~ /\.ht {
# deny all;
#}
}
PHP 文件
<?php
echo "PHP Test";
?>
浏览器响应:下载(chrome)或将其显示为源代码(其他浏览器)
卷曲:
- DNS 缓存中未找到主机名
- 正在尝试::1...
- 已连接到本地主机(::1)端口 80(#0)
GET /test_2.php HTTP/1.1 用户代理:curl/7.38.0 主机:localhost 接受:/
< HTTP/1.1 200 正常
- 服务器 nginx 未被列入黑名单 < 服务器:nginx < 日期:2017 年 5 月 12 日星期五 04:21:20 GMT < 内容类型:text/html;字符集 = UTF-8 < 传输编码:分块 < 连接:保持活动 < PHP 测试
- 与主机 localhost 的连接 #0 保持不变
nginx 访问日志
::1 - - [12/May/2017:12:21:20 +0800] "GET /test_2.php HTTP/1.1" 20019 "-" "curl/7.38.0"
192.168.0.132 - - [12/May/2017:12:26:28 +0800] "GET /test_2.php HTTP/1.1" 200 28 "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.79 Safari/537.36 Edge/14.14393"
nginx 错误日志
2017/05/12 11:50:41 [error] 21715#0: *64 open() "/usr/share/nginx/html/favicon.ico" failed (2: No such file or directory), client: 192.168.0.132, server: ~., request: "GET /favicon.ico HTTP/1.1", host: "192.168.0.113"
2017/05/12 11:53:02 [error] 21715#0: *66 open() "/usr/share/nginx/html/favicon.ico" failed (2: No such file or directory), client: 192.168.0.132, server: ~., request: "GET /favicon.ico HTTP/1.1", host: "192.168.0.113"
2017/05/12 11:54:18 [notice] 21737#0: signal process started
2017/05/12 11:54:22 [notice] 21747#0: signal process started
编辑:在 Tim 的以下评论之后,我运行了 curl 强制 IPv4,它确实返回了源代码。
答案1
我想我知道为什么会这样。我的第二个服务器块使用 RegEx 解析所有名称,~.
设置为侦听端口 80(即 IPv4),并且没有 CGI 处理程序。但是,默认服务器块设置为侦听端口 80(即 IPv6)。由于 nginx 仅在测试其他服务器后才回退到默认服务器,因此代理服务器块无法处理 PHP,因此它将其作为源代码返回。在 IPv6 上,nginx 无法使用代理服务器块来处理请求,因此它将请求传递给运行 FastCGI 服务器的默认服务器,因此它可以返回phpinfo()
。
解决方案
我应该将 location /git/
代理传递块放在默认服务器块中。