CentOS7上使nginx支持PHP

测试代码

1
2
3
<?php
phpinfo();
?>

Nginx访问PHP文件的File not found

这个错误很常见,原有有下面两面几种

    1. php-fpm找不到SCRIPT_FILENAME里执行的php文件
    1. php-fpm不能访问所执行的php,也就是权限问题
第一种情况

更改配置文件nginx.conf

1
fastcgi_param SCRIPT_FILENAME /scripts$fastcgi_script_name;

替换成下面

1
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;

然后重新加载nginx配置文件

1
/etc/init.d/nginx reload

第二种情况

两种解决方法:
第一种,就是把你root文件夹设为其他用户允许
第二种,找到你的php-fpm的配置文件,找到下面这段,把apache替换成你要的用户组

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

正确配置Nginx+PHP

网上错误或是坏味道的配置
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
server {
listen 80;
server_name foo.com;

root /path;

location / {
index index.html index.htm index.php;

if (!-e $request_filename) {
rewrite . /index.php last;
}
}

location ~ \.php$ {
include fastcgi_params;
fastcgi_param SCRIPT_FILENAME /path$fastcgi_script_name;
fastcgi_pass 127.0.0.1:9000;
fastcgi_index index.php;
}
}
正确的配置-使用try_files
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
server {
listen 80;
server_name foo.com;

root /path;
index index.html index.htm index.php;

location / {
try_files $uri $uri/ /index.php$is_args$args;
}

location ~ \.php$ {
try_files $uri =404;

include fastcgi.conf;
fastcgi_pass 127.0.0.1:9000;
}
}
fastcgi.conf
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
fastcgi_param  SCRIPT_FILENAME   $document_root$fastcgi_script_name;  
fastcgi_param QUERY_STRING $query_string;
fastcgi_param REQUEST_METHOD $request_method;
fastcgi_param CONTENT_TYPE $content_type;
fastcgi_param CONTENT_LENGTH $content_length;

fastcgi_param SCRIPT_NAME $fastcgi_script_name;
fastcgi_param REQUEST_URI $request_uri;
fastcgi_param DOCUMENT_URI $document_uri;
fastcgi_param DOCUMENT_ROOT $document_root;
fastcgi_param SERVER_PROTOCOL $server_protocol;
fastcgi_param REQUEST_SCHEME $scheme;
fastcgi_param HTTPS $https if_not_empty;

fastcgi_param GATEWAY_INTERFACE CGI/1.1;
fastcgi_param SERVER_SOFTWARE nginx/$nginx_version;

fastcgi_param REMOTE_ADDR $remote_addr;
fastcgi_param REMOTE_PORT $remote_port;
fastcgi_param SERVER_ADDR $server_addr;
fastcgi_param SERVER_PORT $server_port;
fastcgi_param SERVER_NAME $server_name;

# PHP only, required if PHP was built with --enable-force-cgi-redirect
fastcgi_param REDIRECT_STATUS 200;

详见: https://huoding.com/2013/10/23/290