Nginx userdir with php

you come here with this problem, here’s the solution:

location ~* ^/~(.+?)(/.*\.php)$
{
	alias /home/$1/public_html$2;
	fastcgi_pass  127.0.0.1:9001;
	include fastcgi_params;
	fastcgi_param SCRIPT_FILENAME $request_filename;
}

location ~ ^/~(.+?)(/.*)?$ {
	alias /home/$1/public_html$2;
	index  index.html index.htm index.php;
	autoindex on;
}

Assumption:

  • user’s public html / php files are located at /home/username/public_html directory
  • php is running as php-fpm which listen on port 9001

There’s some solution on the Internet which tried to use nested location

location ~ ^/~(.+?)(/.*)?$ {
	alias /home/$1/public_html$2;
	index  index.html index.htm index.php;
	autoindex on;

	location ~ .+\.php$ {
		fastcgi_pass  127.0.0.1:9001;
		include fastcgi_params;
		fastcgi_param SCRIPT_FILENAME $request_filename;
	}
}

This won’t work, because nginx refer variables by name, and in the nested location, $request_filename(which is a result of alias) refers regex capture $1 and $2, both value are empty. As a result, $request_filename will always be /home//public_html, definitely wrong.

This entry was posted in Web and tagged , , . Bookmark the permalink.

Leave a Reply