两个版本的PHP的Nginx配置


Nginx configuration for two versions of PHP

我正在尝试建立一个nginx环境,在这个环境中,遗留代码和新的MVC风格的代码可以共存,这样我就可以逐步逐页重构它。遗留代码需要一个旧版本的PHP(它在5.3上运行得最好,但我在编译它时遇到了问题,所以我选择了5.4,并将修复任何损坏的代码),但它很容易通过URL区分,因为它有像http://sub.domain.com/search.php?category=4等的文字文件名,而不是像http://sub.domain.com/search/category/4这样的新样式-关键区别在于.php的存在。

新代码在nginx-config中运行良好,如下所示:

server {
  listen 80;
  server_name *.myproject.dev;
  root /var/www/myproject/public;
  index index.php index.html index.htm;
  try_files $uri $uri/ @rewrite;
  location @rewrite {
    rewrite ^/(.*)$ /index.php?_url=/$1;
  }
  location ~ ^(.+'.php)(/.*)?$ {
    fastcgi_param PATH_INFO $fastcgi_path_info;
    fastcgi_param PATH_TRANSLATED $document_root$fastcgi_path_info;
    fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
    fastcgi_pass unix:/var/run/php5-fpm.sock;
    fastcgi_split_path_info ^(.+'.php)(/.+)$;
    include fastcgi_params;
  }
}

(我承认,我并没有完全理解所有的代码——它来自各种指南等等。)

在这个很棒的教程的帮助下,我在自己的位置编译并安装了PHP5.4,监听端口9001。对旧代码使用单独的域可以很好地工作,但我想做的是使用单个域,但如果在URL中找到.php,则调用旧代码,并对其他任何内容进行必要的重写并使用新代码。我在ServerFault上找到了这篇文章,并尝试将它的想法融入我的情况中,如下所示:

server {
  listen 80;
  server_name *.myproject.dev;
  root /var/www/myproject/public;
  index index.php index.html index.htm;
  try_files $uri $uri/ @rewrite;
  location @rewrite {
    rewrite ^/(.*)$ /index.php?_url=/$1;
  }
  location ~ ^(.+'.php)(/.*)?$ {
    fastcgi_param PATH_INFO $fastcgi_path_info;
    fastcgi_param PATH_TRANSLATED $document_root$fastcgi_path_info;
    fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
    fastcgi_pass unix:/var/run/php5-fpm.sock;
    fastcgi_split_path_info ^(.+'.php)(/.+)$;
    include fastcgi_params;
    # Anything with ".php" is directed to the old codebase
    location ~* '.php {
      root /var/www/myproject/oldcode;
      fastcgi_pass 127.0.0.1:9001;
    }
  }
}

但是重写将index.php添加到新代码中,所以最终,所有内容都匹配.php测试,这不是目的。我试着在文件的前面放最后四行,有几个变体,但没有帮助(要么是空白页,要么仍然只转到旧的代码位置,具体取决于细节)。是否有人对nginx-config语法有足够的了解,可以帮助我重新排列它,使其符合我的要求?

如果您的新代码只使用/index.php而没有任何path_info,则可以使用前缀位置:

location ^~ /index.php { ... }
location ~* '.php { ... }

由于^~运算符,第一个位置优先。或者完全匹配(也优先):

location = /index.php { ... }
location ~* '.php { ... }