nginx别名和动态目录名称 [英] nginx aliases and dynamic directory names

查看:605
本文介绍了nginx别名和动态目录名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在这个问题上花了很多钱,但我找不到解决方法. 我需要一种将相同的url指向不同的根目录的方法.我不想使用重写,因为根Directoy名称必须由应用程序处理,并且重写会丢弃它.

I have spent muy tiempo on this and I can't get a solution. I need a way to point the same url but with different root directory to the same application. I don't want to use rewrites because the root directoy name has to be processed by the application and rewrite discards it.

http://www.host.com/a/ --> /var/www/html/project/
http://www.host.com/b/ --> /var/www/html/project/
http://www.host.com/c/ --> /var/www/html/project/

我已经设法在nginx中配置一个别名为固定名称为vdirectory的别名目录,并使nginx将请求转发到fastcgi.

I've managed to configure in nginx an alias directory with a fixed name vdirectory and make nginx forward the request to fastcgi.

location /vdirectory {

      alias /var/www/html/project/;
      try_files $uri $uri/ /vdirectory/index.php;
      location ~ \.php$ {
          fastcgi_pass unix:/var/run/php5-fpm.sock;
          include fastcgi_params;                       
          fastcgi_param SCRIPT_FILENAME $request_filename;
      }
}

以上工作正常.

由于我不想使用固定的根目录名,而是使用任意的根目录名,因此,这是我到目前为止所管理的:

Since I don't want to use fixed root directory names but arbitrary ones, this is what I've managed so far:

location  ~ ^/(.?)$  {

      alias /var/www/html/project/;
      try_files $uri $uri/ /$1/index.php;
      location ~ \.php$ {
          fastcgi_pass unix:/var/run/php5-fpm.sock;
          include fastcgi_params;                       
          fastcgi_param SCRIPT_FILENAME $request_filename;
      }
}

不用说,它返回404.这是一个好兆头,因为它表示正则表达式已识别出该路径,但请求未正确转发.

Needless to say, it returns 404. It is a good sign because it means regex has recognized the path, but the request isn't forwarded correctly.

工作配置和错误配置之间的唯一区别是/vdirectory~ ^/(.?)$

The only difference between the working config and the wrong one is /vdirectory vs ~ ^/(.?)$

推荐答案

alias在正则表达式location块中时的工作方式有所不同.有关详细信息,请参见本文档.您将需要捕获URI的其余部分,并将其附加到alias值.例如:

alias works differently when inside a regular expression location block. See this document for details. You will need to capture the remainder of the URI and append that to the alias value. For example:

location ~ ^/(?<prefix>[^/]+)/(?<name>.*)$ {
    alias /var/www/html/project/$name;

    if (!-e $request_filename) { rewrite ^ /$prefix/index.php last; }

    location ~ \.php$ {
        if (!-f $request_filename) { return 404; }

        fastcgi_pass unix:/var/run/php5-fpm.sock;
        include fastcgi_params;                       
        fastcgi_param SCRIPT_FILENAME $request_filename;
    }
}

由于长期问题,我避免在同一块中使用try_filesalias .有关使用if的信息,请参见此警告.

I avoid using try_files and alias within the same block due to long term issues. See this caution on the use of if.

这篇关于nginx别名和动态目录名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆