[Yii2] Nginx 配置 – 讓PHP全進framework – nginx php location try_files

原由

這邊主要是要解決yii2 UrlManager應用中,網址內含.php的路由會導至nginx 404 Not Found問題。

原因為yii2官方建議的Nginx配置:

location / {
    # Redirect everything that isn't a real file to index.php
    try_files $uri $uri/ /index.php$is_args$args;
}

location ~ \.php$ {
    include fastcgi_params;
    fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
    fastcgi_pass 127.0.0.1:9000;
    #fastcgi_pass unix:/var/run/php5-fpm.sock;
    try_files $uri =404;
}

http://www.yiiframework.com/doc-2.0/guide-start-installation.html

在PHP Location中try_files $uri =404;即匹配不到的.php檔案則跳404,但我們一般情況應是要全部網址路由都交給Framework處理才對。


解決方法

既然PHP Location也要同通配符:找不到的都進Framework,所以原來的通用try_files就是解:

try_files $uri $uri/ /index.php$is_args$args;

將PHP Location內的try_files取代,設定後範例:

location / {
    # Redirect everything that isn't a real file to index.php
    try_files $uri $uri/ /index.php$is_args$args;
}

location ~ \.php$ {
    include fastcgi_params;
    fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
    fastcgi_pass 127.0.0.1:9000;
    #fastcgi_pass unix:/var/run/php5-fpm.sock;
    #try_files $uri =404;
    try_files $uri $uri/ /index.php$is_args$args;
}

這樣的設定應當會符合多數需求,凡舉例新舊系統轉移,舊版.php網址當然由新版yii2 UrlManager吃下做轉導(不建議在nginx內寫rewirte)。


yii 1.1官方解法

yii 1.1 Apache and Nginx configurations

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

    #let yii catch the calls to unexising PHP files
    set $fsn /$yii_bootstrap;
    if (-f $document_root$fastcgi_script_name){
        set $fsn $fastcgi_script_name;
    }

    fastcgi_pass   127.0.0.1:9000;
    include fastcgi_params;
    fastcgi_param  SCRIPT_FILENAME  $document_root$fsn;

    #PATH_INFO and PATH_TRANSLATED can be omitted, but RFC 3875 specifies them for CGI
    fastcgi_param  PATH_INFO        $fastcgi_path_info;
    fastcgi_param  PATH_TRANSLATED  $document_root$fsn;
}

Leave a Reply

Your email address will not be published. Required fields are marked *