Nginx alias directive not working with php

2019-06-24 16:59发布

I have an app that is running on Nginx with a working server block like so:

server {

  listen 80;
  server_name example.com;
  root /home/deployer/apps/my_app/current/;
  index index.php;

  location / {
    index index.php;
    try_files $uri $uri/;
  }

  location ~ \.php$ {
    try_files $uri =404;
    fastcgi_split_path_info ^(.+\.php)(/.+)$;
    fastcgi_pass unix:/home/deployer/apps/shared/php5-fpm.sock;
    fastcgi_index index.php;
    include fastcgi_params;
  }

  location /foo {
    root /home/deployer/apps/modules/;
    # tried this:
    # alias /home/deployer/apps/modules/foo/;
    # but php is not working with alias, only with root
  }

}

When I visit /foo, Nginx looks in the path /home/deployer/apps/modules/foo/ for an index.php file and it works.

The problem:

I set up a deploy script using capistrano that deploys to the foo directory:

/home/deployer/apps/modules/foo/

Capistrano creates a 'current' directory within the 'foo' directory to contain the application files pulled in from Github, so I needed to change the root path to be:

/home/deployer/apps/modules/foo/current/

But Nginx appends the location directive to the end of the root directive.... so, when you visit /foo, Nginx tries to look in:

/home/deployer/apps/modules/foo/current/foo/

Using alias is supposed to disregard the /foo set in the location directive and serve files from the exact alias path (which the logs confirm is happening), but when I use the alias directive, the php configuration is not being applied correctly and I am getting a 404 returned.

If I go back to the root directive and remove the 'current' directory altogether, it works fine. I need the files to be served from the 'current' directory to work smoothly with the Capistrano deploy, but cannot figure out how to make the alias directive work with php.

Anyone have any ideas or advice, am I missing something?

标签: nginx php server
2条回答
Root(大扎)
2楼-- · 2019-06-24 17:50

thanks to @xavier-lucas for the suggestion about not being able to use try_files with alias.

To use alias with php, I had to remove the try_files directive from the php location block shown in the original question:

try_files $uri =404;

I actually had to restate the php location block within the /foo location and remove the above line. It ended up looking like this:

location /foo {
  alias /home/deployer/apps/modules/foo/;
  location ~ \.php$ {
    # try_files $uri =404; -- removed this line
    fastcgi_split_path_info ^(.+\.php)(/.+)$;
    fastcgi_pass unix:/home/deployer/apps/shared/php5-fpm.sock;
    fastcgi_index index.php;
    include fastcgi_params;
  }
}

This allows php files to be processed directly from the directory listed in the alias directive.

查看更多
女痞
3楼-- · 2019-06-24 17:51

Use

location /foo/ {
    alias /home/deployer/apps/modules/foo/current/;
}

instead of

location /foo {
    alias /home/deployer/apps/modules/foo/;
}
查看更多
登录 后发表回答