Nginx – How to correctly use the NginX location directive

configurationfastcginginxPHP

I am attempting to use the phpmyadmin package installed via apt on Ubuntu 10.10 with NginX and although I eventually got it to work, I don't think I'm doing it correctly:

server {
  listen   80; ## listen for ipv4

  server_name  vpsnet.dev;

  error_log   /home/robin/dev/vpsnet/error.log;
  access_log  /var/log/nginx/vpsnet.access.log;

  location / {
    root   /home/robin/dev/vpsnet/webroot;
    index  index.php index.html;

    if (-f $request_filename) {
        break;
    }

    if (!-f $request_filename) {
        rewrite ^/(.+)$ /index.php?url=$1 last;
        break;
    }
  }

  location /phpmyadmin {
    root /usr/share;
    index index.php index.html;
  }

  location ~ ^/phpmyadmin/.*\.php$ {
    fastcgi_pass 127.0.0.1:9000;
    fastcgi_index index.php;
    fastcgi_param SCRIPT_FILENAME /usr/share/$fastcgi_script_name;
    include /etc/nginx/fastcgi_params;
    fastcgi_param SERVER_NAME $host;
  }

  location ~ \.php$ {
    fastcgi_pass 127.0.0.1:9000;
    fastcgi_index index.php;
    fastcgi_param SCRIPT_FILENAME /home/robin/dev/vpsnet/webroot/$fastcgi_script_name;
    include /etc/nginx/fastcgi_params;
    fastcgi_param SERVER_NAME $host;
  }
}

The part I'm talking about is this part in particular:

  location /phpmyadmin {
    root /usr/share;
    index index.php index.html;
  }

  location ~ ^/phpmyadmin/.*\.php$ {
    fastcgi_pass 127.0.0.1:9000;
    fastcgi_index index.php;
    fastcgi_param SCRIPT_FILENAME /usr/share/$fastcgi_script_name;
    include /etc/nginx/fastcgi_params;
    fastcgi_param SERVER_NAME $host;
  }

If I set the root directive to /usr/share/phpmyadmin and respectively the fastcgi_param SCRIPT_FILENAME to /usr/share/phpmyadmin/$fastcgi_script_name; I get a 404.

I imagine that the server is passing the /phpmyadmin/ part of the URL to the fastcgi server, but I am confused by this, as I come from using Apache and that's not how this kind of thing worked with that.

I'm just wondering if anyone can shed some light on this, why it acts like this, and if I'm doing anything wrong. A "perfect" setup would be great, or at least some information on how to better understand NginX configuration.

Best Answer

See if that works:

location /phpmyadmin {
  alias /usr/share/phpmyadmin;
  index index.php index.html;
}

location ~ .php$ {
  fastcgi_pass 127.0.0.1:9000;
  fastcgi_index index.php;
  fastcgi_param SCRIPT_FILENAME /usr/share/$fastcgi_script_name;
  include /etc/nginx/fastcgi_params;
  fastcgi_param SERVER_NAME $host;
}

Your config is not wrong or anything. Using root inside location blocks is not advised because if you get a lot of location blocks it starts to get messy (so it's better to have one root per server block) but that's not your case, and the fastcgi settings are usually done on a broader manner (for all php requests).