1. 程式人生 > >CodeIgniter框架中 Nginx伺服器下去掉index.php

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;
    }

} |

具體的改動已經標註在上面的註釋中了,很簡單的一句重寫規則,我卻折騰了蠻久的時間。希望分享出來,幫助大家少踩坑。就寫到這裡吧!