Nginx下alias支持PHP的问题

标签 : ,

这几天在配置Nginx,PHP用FastCGI,想装一个phpMyAdmin管理数据库,phpMyAdmin不想放在网站根目录下,这样不容易和网站应用混在一起,这样phpMyAdmin的目录就放在别处,在Apache里,有alias,比较方便,在Nginx下没有虚拟目录概念的,是用location配合alias使用,我先试了简单的配置方式

location /web/ {
alias  /data/web/;
index  index.html index.htm index.php;
}

location ~ .*\.(php|php5)?$ {
fastcgi_pass  127.0.0.1:9000;
fastcgi_index index.php;
include fcgi.conf;
}

我用http://localhost/web/可以访问到/data/web目录下的静态文件,但访问php文件,却报No input file specified.的错误,而且在Nginx的error日志上却什么信息也没有,我在网上搜索了一下,判断应该是php文件并没有被后端的FastCGI运行,我又继续搜索一些文章,试着增加了一段配置

location /web/ {
alias  /data/web/;
index  index.html index.htm index.php;
}

location ~ ^/web/.+\.php$ {
root /data/;
rewrite /web/(.*\.php?) /$1 break;
include fcgi.conf;
fastcgi_pass   127.0.0.1:9000;
fastcgi_index  index.php;
fastcgi_param SCRIPT_FILENAME /data/web$fastcgi_script_name;
}

location ~ .*\.(php|php5)?$ {
fastcgi_pass  127.0.0.1:9000;
fastcgi_index index.php;
include fcgi.conf;
}

这下可以了,原理应该是采用rewrite的方法,对于/web/下php类型的的请求交给后端的FastCGI处理,并且指定了php脚本的位置,这样我们就可以配置phpMyAdmin了,配置如下

location /phpmyadmin/ {
alias  /data/phpmyadmin/;
index  index.html index.htm index.php;
}

location ~ ^/phpmyadmin/.+\.php$ {
root /data/;
rewrite /phpmyadmin/(.*\.php?) /$1 break;
include fcgi.conf;
fastcgi_pass   127.0.0.1:9000;
fastcgi_index  index.php;
fastcgi_param SCRIPT_FILENAME /data/phpmyadmin$fastcgi_script_name;
}

location ~ .*\.(php|php5)?$ {
fastcgi_pass  127.0.0.1:9000;
fastcgi_index index.php;
include fcgi.conf;
}

要注意的是

location ~ .*\.(php|php5)?$ {
fastcgi_pass  127.0.0.1:9000;
fastcgi_index index.php;
include fcgi.conf;
}

这段,要放在phpmyadmin的后面,放在前面就有问题,这是和Nginx的location规则有关,具体看Nginx的文档,另外,phpMyAdmin里要配置一下URI的绝对路径,就可以了。

发表评论

*
To prove you're a person (not a spam script), type the security word shown in the picture. Click on the picture to hear an audio file of the word.
Click to hear an audio file of the anti-spam word