有条件地在NGINX中添加url路径

时间:2016-09-16 13:49:33

标签: nginx url-rewriting

我的项目目录结构

/var/www
  /project-a
     /data    <-- configuration and user files/data 
     /app     <-- all the code is in sub-dirs in here
     /pm      <-- a home brew project management app
     /.pmdata <-- data used by pm

我的目标是配置NGINX,以便我可以通过自己访问项目 http://project-a.dev/以及http://project-a.dev/pm/的项目管理。

换句话说,我希望第二个网址按原样保留,但如果网址未指向/pm/*,则应重新编写该网址以将缺少的/app添加到其中。

我尝试了以下配置,但http://project-a.dev/pm/导致404和http://project-a.dev/首先重定向到http://project-a.dev/app/,然后给出404。

我做错了什么?

server {
    listen 127.0.0.1:80;
    root /var/www/project-a;
    index index.php index.html index.htm;
    server_name project-a.dev;
    location / {
        try_files $uri $uri/app $uri/app/ =404;
    }
    location ~ \.php$ {
        try_files $uri =404;
        fastcgi_split_path_info ^(.+\.php)(/.+)$;
        fastcgi_pass unix:/var/run/php5-fpm.sock;
        fastcgi_index index.php;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        include fastcgi_params;
    }
}

1 个答案:

答案 0 :(得分:1)

或者,对于不以/app开头的所有URI,您可以将root附加到/pm值。例如:

server {
    ...
    root /var/www/project-a/app;
    index index.php index.html index.htm;
    location / {
        try_files $uri $uri/ =404;
    }
    location ~ \.php$ {
        try_files $uri =404;
        fastcgi_pass unix:/var/run/php5-fpm.sock;
        include fastcgi_params;
        fastcgi_param SCRIPT_FILENAME $request_filename;
    }
    location ^~ /pm {
        root /var/www/project-a;
        try_files $uri $uri/ =404;

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

location ~ \.php$的嵌套位置块在/pm层次结构中执行PHP文件。 ^~修饰符是必要的,以避免其他location ~ \.php$块控制。有关详细信息,请参阅this document