CodeIgniter框架中 Nginx服务器下去掉index.php

上文中提到的Apache去掉index.php在官方帮助文档也有简要的说明,但是Nginx服务器就没有这么幸运了。我在网站开发时本地是Apache,但是网站上线时的服务器却是Nginx的,因此不得已又去网上搜索Nginx服务器下的配置,折腾了很久,试错试了很多次,总算把一个正确的版本试出来了,现在可以提供给大家参考。因为自己对于Nginx的配置没有深入研究过,所以先说明一下自己线上服务器用的环境,然后再展示Nginx配置的修改内容。以我目前的配置,亲测可以很好地工作,大家碰到了类似的问题可以按照我的配置尝试一下,不过我也不敢保证在您的系统上一定会奏效……我的线上服务器是买的XX云(避免广告~)服务器(自己从零开始搞一个服务器实在太麻烦了),系统配置好之后默认就是Nginx。操作系统采用的是Ubuntu 12.04,Nginx版本是nginx/1.1.19。

看网上好多人的Nginx服务器默认配置文件是/etc/nginx/nginx.conf,我的也不例外。不过有个注意事项,有时候nginx.conf中会有一句include ***(另外一个文件),也就是引用外边某个文件的内容作为配置文件,这时候,如果你没有在nginx.conf中找到服务器server相关配置,不妨去它include的另外一个文件中找一下,我的就是这种情况。在我的配置文件中,和服务器有关的配置应该改成如下:

server {
    listen   80;

    root /usr/share/nginx/www;
    index index.php index.html index.htm;

    # Make site accessible from http://localhost/
    server_name localhost;

    location / {
            index index.php index.html index.htm;
            
            # Uncomment to enable naxsi on this location
            # include /etc/nginx/naxsi.rules

            # 请留意下面这条重写规则,和前面的Apache有些类似
            if (!-e $request_filename) { ##如果没有找到目标文件
                    rewrite ^/(.*)$ /index.php/$1 last;
                    break;
            }

# 上面的重写规则也可以改成下面这种形式,亲测两者都可行
          # if (KaTeX parse error: Can't use function '\.' in math mode at position 45: …s|images|robots\̲.̲txt|index\.php.… /index.php/$1 last;
          # break;
          # }
}

    location /doc/ {
            alias /usr/share/doc/;
            autoindex on;
            allow 127.0.0.1;
            deny all;
    }

    location ~ \.php($|/) {
            fastcgi_split_path_info ^(.+\.php)(.*)$;

            fastcgi_pass 127.0.0.1:9000;
  
            fastcgi_index index.php;
            fastcgi_param PATH_INFO $fastcgi_path_info;
            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;
    }

} |

具体的改动已经标注在上面的注释中了,很简单的一句重写规则,我却折腾了蛮久的时间。希望分享出来,帮助大家少踩坑。就写到这里吧!

猜你喜欢

转载自blog.csdn.net/qq_34698708/article/details/83547780
今日推荐