试图首先使用相同的路线使用nginx回退到cakephp来提供文件

时间:2018-03-13 22:05:16

标签: file nginx cakephp static

我们目前正在从apache迁移,并且使用nginx我必须能够在api/webroot内提供文件并使用CakePHP执行php脚本。例如,路由/api/login应由CakePHP解析,而/api/picture/pic.png应作为静态文件提供。

我正在尝试使用回退来解决此问题,但似乎try_files无法解决回退@cakephp,而是立即返回404错误。

我当前损坏的网站配置如下:

server {
    listen 80;
    listen [::]:80;

    root /home/user/site;
    index index.html;

    server_name localhost;

    location /api {
        set $path "";
        if ( $request_uri ~* "^/api/(.*)$" ) {
            set $path $1;
        }
        try_files /api/webroot/$path /api/webroot/$path/ @cakephp;
    }

    location @cakephp {
        try_files $uri $uri/ /api/webroot/index.php?$args;
    }

    location / {
        try_files $uri $uri/ /api/webroot/index.php?$args;
    }

    location ~ \.php$ {
        try_files $uri =404;
        include fastcgi_params;
        fastcgi_pass unix:/var/run/php/php7.0-fpm.sock;
        fastcgi_index index.php;
        fastcgi_intercept_errors on;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
    }
}

1 个答案:

答案 0 :(得分:0)

我们通过在路线上添加限制并将其与正则表达式匹配来解决它

server {
    listen 80;
    listen [::]:80;

    # listen 443 ssl;
    # listen [::]:443 ssl;

    root /home/user/site;

    # Add index.php to the list if you are using PHP
    index index.html;

    location ~* ^/api/(.*[^(php)])$ {
        add_header X-debug-message "$1" always;
        try_files /api/webroot/$1 @cakephp;
    }

    location @cakephp {
        add_header X-debug-message "$uri" always;
        try_files $uri $uri/ /api/webroot/index.php?$args;
    }

    location / {
        add_header X-debug-message "root" always;
        try_files $uri $uri/ =404;
    }

    location ~ \.php$ {
        try_files $uri =404;
        include fastcgi_params;
        fastcgi_pass unix:/var/run/php/php7.0-fpm.sock;
        fastcgi_index /api/webroot/index.php;
        fastcgi_intercept_errors on;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        add_header X-uri "$uri" always;
    }
}