由于CodeIgniter当初是设计在apache的,而apache对pathinfo是支持比较好的,所以一切都很nice。但是当你把写好的代码放到nginx上,傻眼了,可能出了CodeIgniter的welcom之外,其他都是404错误。而我惊奇的发现,CodeIgniter的官方文档竟然对在Nginx上的配置只字不提。而你百度”CodeIgniter Nginx 404”又能搜到一堆一堆的文章,奇葩的是几乎每个文档的配置方法貌似还不大一样。如果你搞好了还罢,搞不好就是配几个晚上都搞不定,像我一样。
404错误的原因
原因是默认Nginx不支持pathinfo这种格式,当你浏览器里输入http:\xxx.xxx.com\index.php\pages\home的时候,Nginx会认为你要访问index.php目录下的pages文件夹里的home,所以会报404 not found错误。
解决方法
解决方法肯定是要修改服务器的重定向规则,大概有两种思路,一种是改nginx安装目录里的nginx.conf文件,如果你用了虚拟主机的话就去nginx安装目录下的vhosts下找对应的*.conf更改即可。
修改之前的nginx.conf文件:
server {
listen 80;
server_name localhost;
#charset koi8-r;
#access_log logs/host.access.log main;
location / {
root D:/wnmp/www;
index index.html index.htm index.php;
}
#error_page 404 /404.html;
# redirect server error pages to the static page /50x.html
#
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root html;
}
# proxy the PHP scripts to Apache listening on 127.0.0.1:80
#
#location ~ \.php$ {
# proxy_pass http://127.0.0.1;
#}
# pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
#
location ~ \.php$ {
root D:/wnmp/www;
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;
#}
}
只需要加入phpinfo支持即可:
fastcgi_split_path_info ^(.+\.php)(.*)$;
fastcgi_param PATH_INFO $fastcgi_path_info;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
fastcgi_param PATH_TRANSLATED $document_root$fastcgi_path_info;
修改后的nginx.conf文件:
server {
listen 80;
server_name localhost;
#charset koi8-r;
#access_log logs/host.access.log main;
location / {
root D:/wnmp/www;
index index.html index.htm index.php;
}
#error_page 404 /404.html;
# redirect server error pages to the static page /50x.html
#
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root html;
}
# proxy the PHP scripts to Apache listening on 127.0.0.1:80
#
#location ~ \.php$ {
# proxy_pass http://127.0.0.1;
#}
# pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
#
location ~ \.php$ {
root D:/wnmp/www;
fastcgi_pass 127.0.0.1:9000;
fastcgi_index index.php;
fastcgi_split_path_info ^(.+\.php)(.*)$;
fastcgi_param PATH_INFO $fastcgi_path_info;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
fastcgi_param PATH_TRANSLATED $document_root$fastcgi_path_info;
include fastcgi_params;
}
# deny access to .htaccess files, if Apache's document root
# concurs with nginx's one
#
#location ~ /\.ht {
# deny all;
#}
}
或者修改如下配置即可:
location / {
root D:/wnmp/www;
index index.html index.htm index.php;
try_files $uri $uri/ /index.php?$uri&$args;
}
修改完nginx配置文件之后重启nginx即可:
nginx -t 检查配置文件有无错误
D:\wnmp\nginx>nginx -t
nginx: the configuration file D:\wnmp\nginx/conf/nginx.conf syntax is ok
nginx: configuration file D:\wnmp\nginx/conf/nginx.conf test is successful
nginx -s reload 重启nginx服务器