M HYPE SPLASH
// general

Nginx cannot find ~/public_html/info.php

By Michael Henderson

I am new to PHP and want to learn it. So I install Nginx, PHP, MariaDB in my computer:

  1. Ubuntu 18.04 LTS 64-bit.
  2. Nginx (don't know how to check version)
  3. PHP 7.2
  4. The default www is /var/www/html. It works fine for HTML and PHP file. (info.php only contain phpinfo();)
  5. A normal user with directory ~/public_html/index.html and info.php. index.html could shown (Hello world), but info.php (same as above) got 404.

/etc/nginx/site-available/default

server {
listen 80 default_server;
listen [::]:80 default_server;
root /var/www/html;
index index.php index.html index.htm index.nginx-debian.html;
server_name _;
location / { try_files $uri $uri/ =404;
}
location ~ \.php$ { fastcgi_split_path_info ^(.+\.php)(/.+)$; include snippets/fastcgi-php.conf; fastcgi_pass unix:/var/run/php/php7.2-fpm.sock; include fastcgi_params;
}
location ~ /\.ht { deny all;
}
location ~ ^/~(.+?)(/.*)?$ { alias /home/$1/public_html$2; index index.php index.html index.htm; autoindex on;
}
}

Please help.

1 Answer

You have PHP files in two roots, so you need two location blocks to process those URIs. The simplest solution is to use a nested location block.

For example:

location / { try_files $uri $uri/ =404;
}
location ~ /\.ht { deny all;
}
location ~ ^/~(?<user>[^/]+)(?<path>/.*)?$ { alias /home/$1/public_html$2; index index.php index.html index.htm; autoindex on; location ~ \.php$ { if (!-f $request_filename) { return 404; } include snippets/fastcgi-php.conf; fastcgi_pass unix:/var/run/php/php7.2-fpm.sock; include fastcgi_params; fastcgi_param SCRIPT_FILENAME $request_filename; }
}
location ~ \.php$ { ...
}

Place the outer location ~ \.php$ block below, otherwise it will match all PHP URIs first. See this document for details.

Use named captures, as numeric captures will be out of scope in the nested location block.

I don't know what's in your snippets file, but you probably want to avoid try_files (because of this issue with alias) and you need to use $request_filename to locate the path to the SCRIPT_FILENAME.

The if block is added to avoid passing uncontrolled requests to PHP. See this caution on the use of if.

2

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy