Configuring nginx virtual hosts

elvispt asked:

I’m having trouble configuring nginx virtual hosts on a Debian GNU/Linux 7 (wheezy) machine.

All I get is a 500 Internal Server Error.

Here is an example of my vhost_autogen.conf file:

server {
  listen                *:80;

  server_name           api-dev.domain.com;

  access_log            /var/log/nginx/api-dev.domain.com.access.log;
  error_log             /var/log/nginx/api-dev.domain.com.error.log;

  location / {
    root  /code/api.domain.com/public;
    try_files  $uri $uri/ /index.php?$args;
    index  index.html index.htm index.php;
  }

  location ~ .php$ {
    root  /code/api.domain.com/public;
    try_files  $uri $uri/ /index.php?$args;
    index  index.html index.htm index.php;
    fastcgi_index index.php;
    fastcgi_param PATH_INFO $fastcgi_path_info;
    fastcgi_param PATH_TRANSLATED $document_root$fastcgi_path_info;
    fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
    fastcgi_param APP_ENV dev;

    fastcgi_pass unix:/var/run/php5-fpm.sock;
    fastcgi_split_path_info ^(.+.php)(/.+)$;
    include fastcgi_params;
  }

}

Permission issue is almost certainly is not, since I gave full permissions (777), just to be sure.

Any hints?

Here is the error log:

2013/12/22 17:08:11 [error] 4341#0: *16 rewrite or internal redirection cycle while internally redirecting to "/index.php", client: 192.168.56.1, server: api-dev.domain.com, request: "GET / HTTP/1.1", host: "api-dev.domain.com"

Thanks for the help.

My answer:


You have wrong try_files inside both of your location blocks.

try_files  $uri $uri/ /index.php?$args;

When it hits $uri/ this causes nginx to look for every file specified in the index directive. It hits on index.php, goes to your second location, and that’s where it seems to get stuck in a loop.

I would rewrite these as:

location / {
    try_files $uri $uri/ /index.php?$args;
}
location ~ .php$ {
    try_files $uri =404;
}

The second location does not need an index directive at all.


View the full question and answer on Server Fault.

Creative Commons License
This work is licensed under a Creative Commons Attribution-ShareAlike 3.0 Unported License.