鍍金池/ 問答/PHP  Linux/ nginx配置php接口多版本,不同版本指向不同目錄

nginx配置php接口多版本,不同版本指向不同目錄

問一個nginx配置php的問題

server {
    listen       80;
    server_name t.timophp.com;

    charset utf-8;
    access_log off;
    
    location /v1 {
        root /data/a/b;
        index   index.php index.html index.htm;
        if (!-e $request_filename) {
            rewrite ^/v1/(.*)$ /index.php/$1 last;
        }
    }

    location /v2/ {
        root /data/c/d;
        index   index.php index.html index.htm;
        if (!-e $request_filename) {
            rewrite ^/v2/(.*)$ /index.php/$1 last;
        }
    }

    location ~ \.php(/|$) {
        fastcgi_split_path_info ^(.+?\.php)(/.*)$;
        fastcgi_pass   unix:/dev/shm/php-fpm.sock;
        fastcgi_index  index.php;
        fastcgi_param  SCRIPT_FILENAME  $document_root$fastcgi_script_name;
        fastcgi_param  PATH_INFO        $fastcgi_path_info;
        include        fastcgi_params;
    }
    
    location ~ /\.ht {
        deny  all;
    }
}

一個域名下面配置多個版本接口
版本一

路徑/data/a/b

版本二

路徑/data/c/d

版本三

路徑/data/e/f

按照我的配置行不通

回答
編輯回答
拽很帥

rewrite

2017年12月10日 17:54
編輯回答
冷溫柔

你這個是報404了
因為并不知道你的 /index.php 是在哪個目錄
把access_log打開,加上error_log看看吧

試下以下配置

server {
    listen       80;
    server_name t.timophp.com;

    charset utf-8;
    access_log off;

    location /v1/ {
        alias /data/a/b/;
        index   index.php index.html index.htm;
        if (!-e $request_filename) {
            rewrite ^/v1/(.*)$ /index.php/$1 last;
        }
        location ~ \.php(/|$) {
            fastcgi_split_path_info ^(.+?\.php)(/.*)$;
            fastcgi_pass   unix:/dev/shm/php-fpm.sock;
            fastcgi_index  index.php;
            fastcgi_param  SCRIPT_FILENAME  $document_root$fastcgi_script_name;
            fastcgi_param  PATH_INFO        $fastcgi_path_info;
            include        fastcgi_params;
        }
    }

    location /v2/ {
        alias /data/c/d/;
        index   index.php index.html index.htm;
        if (!-e $request_filename) {
            rewrite ^/v2/(.*)$ /index.php/$1 last;
        }
        location ~ \.php(/|$) {
            fastcgi_split_path_info ^(.+?\.php)(/.*)$;
            fastcgi_pass   unix:/dev/shm/php-fpm.sock;
            fastcgi_index  index.php;
            fastcgi_param  SCRIPT_FILENAME  $document_root$fastcgi_script_name;
            fastcgi_param  PATH_INFO        $fastcgi_path_info;
            include        fastcgi_params;
        }
    }

    location ~ /\.ht {
        deny  all;
    }
}
2017年7月8日 07:22
編輯回答
吃藕丑
2017年3月1日 23:30
編輯回答
膽怯

除了 nginx 里配置,其實還有2種思路:

把 v1, v2 作為 module;

入口文件里重寫:

if (preg_match('/^\/v(\d+)/', $_SERVER['REQUEST_URI'], $matches)) {
    $arr = [
        1 => '/data/a/b',
        2 => '/data/c/d',
    ];
    include $arr[$matches[1]] . '/index.php';
}
2018年2月22日 03:17