Majid Fouladpour
Majid Fouladpour

Reputation: 30272

Conditionally prepend path to url in NGINX

I have this directory structure for my projects

/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

My goal is to configure NGINX so I can access the project itself through http://project-a.dev/ and the project management with http://project-a.dev/pm/.

In other words, I want the second url preserved as is, but if the url does not point to /pm/* it should be re-written to have the missing /app prepended to it.

I have tried the following configuration but http://project-a.dev/pm/ results in 404 and http://project-a.dev/ first redirects to http://project-a.dev/app/ and then gives 404.

What am I doing wrong?

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;
    }
}

Upvotes: 1

Views: 1512

Answers (1)

Richard Smith
Richard Smith

Reputation: 49812

Alternatively you could append /app to the root value for all URIs that do not begin with /pm. For example:

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;
        }
    }
}

The nested location block for location ~ \.php$ executes PHP files within the /pm hierarchy. The ^~ modifier is necessary to avoid the other location ~ \.php$ block taking control. See this document for details.

Upvotes: 1

Related Questions