在CentOS上安装完Nginx后,Nginx默认只支持静态页面,当收到动态页面请求时,Nginx将其交给PHP来处理。本文主要介绍CentOS上Nginx Alias发布虚拟目录及支持PHP配置方法。
在安装LAMP时,已经安装了如下模块
yum install php-mysql php-common
php-mbstring php-gd
php-imap php-ldap
php-odbc php-pear
php-xml php-xmlrpc
继续安装如下模块
1 | yum install php-fpm php-cli php-mcrypt php-mssql php-snmp php-soap php-tidy |
配置remi源
2 | yum install yum-priorities |
1 | vi /etc/yum.repos.d/remi.repo |
在文件中写入
3 | name=Les RPM de remi pour Enterprise Linux $releasever - $basearch |
17 | failovermethod=priority |
安装php-fpm
1 | yum install php-fpm php-cli php-gd php-mysql |
2. 编辑php.ini
在文件结尾处添加
3. 启动php-fpm
2 | chkconfig --levels 235 php-fpm on |
4. 建立测试主页index.php
Nginx默认的发布目录是/usr/share/nginx/html,在此文件夹下建立测试主页
1 | vi /usr/share/nginx/html/index.php |
写入如下内容
1 | vi /etc/nginx/nginx.conf |
进行如下修改(可直接覆盖原文件)
9 | #access_log logs/host.access.log main; |
13 | root /usr/share/nginx/html; |
15 | index index.php index.html index.htm; |
19 | error_page 404 /404.html; |
21 | location = /404.html { |
23 | root /usr/share/nginx/html; |
27 | # redirect server error pages to the static page /50x.html |
31 | error_page 500 502 503 504 /50x.html; |
33 | location = /50x.html { |
35 | root /usr/share/nginx/html; |
39 | # proxy the PHP scripts to Apache listening on 127.0.0.1:80 |
49 | # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000 |
55 | root /usr/share/nginx/html; |
57 | fastcgi_pass 127.0.0.1:9000; |
59 | fastcgi_index index.php; |
61 | fastcgi_param SCRIPT_FILENAME /usr/share/nginx/html$fastcgi_script_name; |
63 | include fastcgi_params; |
67 | # deny access to .htaccess files, if Apache's document root |
69 | # concurs with nginx's one |
6. 重启相关服务
2 | service php-fpm restart |
这时访问http://localhost:8080打开Nginx默认的php测试主页,如下

Nginx中有alias与root两种标签,最基本的区别是:alias指定的目录是准确的,root是指定目录的上级目录,并且该上级目录要含有location指定名称的同名目录。如:
3 | index index.html index.htm ; |
这种配置下http://localhost/lovesoo指定的是/media/lovesoo
3 | index index.html index.htm ; |
这种配置下,访问http://localhost/lovesoo时,Nginx会去找/media目录下的lovesoo文件夹
Nginx也有与Apache类型的alias功能,示例配置如下
3 | index index.html index.htm ; |
8. php支持配置
首先建立index.php测试文件
1 | vi /media/lovesoo/index.php |
写入如下内容
1 | vi /etc/nginx/nginx.conf |
在nginx配置文件中添加如下配置
5 | index index.php index.html index.htm; |
9 | location ~ /lovesoo/.+\.php.*$ { |
11 | if ($fastcgi_script_name ~ /lovesoo/(.+\.php.*)$) { |
13 | set $valid_fastcgi_script_name $1; |
17 | fastcgi_pass 127.0.0.1:9000; |
19 | fastcgi_index index.php; |
21 | fastcgi_param SCRIPT_FILENAME /media/lovesoo/$valid_fastcgi_script_name; |
23 | include fastcgi_params; |
重启nginx及php-fpm服务
2 | service php-fpm restart |
访问http://localhost:8080/lovesoo,即可正常访问测试主页index.php
