пятница, 13 декабря 2019 г.

Nginx 403 error directory index of is forbidden, client 1.2.3.4

There wasn't index index.php; in config file in my case.

https://www.ionos.com/community/server-cloud-infrastructure/nginx/solve-an-nginx-403-forbidden-error/

Nginx php in subdirectory

Wordpress is in sub-directory nested, and blog address is domain.tld/nested

useful links
https://serversforhackers.com/c/nginx-php-in-subdirectory
https://www.nginx.com/resources/wiki/start/topics/tutorials/config_pitfalls/

server {
  listen 80 default_server; 
  listen [::]:80 default_server; 
  root /var/www/top/public; 
  index index.html index.htm index.php; 
  server_name _; 

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

  location /nested { 
    alias /var/www/nested/public; 
    try_files $uri $uri/ @nested; 

    location ~ \.php$ { 
      index index.php;
      include snippets/fastcgi-php.conf; 
      fastcgi_param SCRIPT_FILENAME $request_filename; 
      fastcgi_pass unix:/var/run/php/php7.2-fpm.sock; 
    } 
  } 
  location @nested { 
    rewrite /nested/(.*)$ /nested/index.php?/$1 last; 
  } 
  location ~ \.php$ { 
    include snippets/fastcgi-php.conf; 
    fastcgi_pass unix:/var/run/php/php7.2-fpm.sock; 
  }
}

Short explanations.

1) root of blog is not domain as domain.tld, but it is address location as domain.tld/nested. So there should be rewrite rule:

    rewrite /nested/(.*)$ /nested/index.php?/$1 last;

2) We use alias, because of explanation from one of useful links below.
Note that distinction - with that alias, Nginx does NOT look for files within /var/www/nested/public/nested/foo, like it would with the root directive.

3) We use $request_filename instead of $document_root$fastcgi_script_name because of next explanation.
If you use the alias directive with $document_root$fastcgi_script_name, $document_root$fastcgi_script_name will return the wrong path.
Request /api/testing.php:
  • $document_root$fastcgi_script_name == /app/www//api/testing.php
  • $request_filename == /app/www/testing.php
Request /api/:
  • $document_root$fastcgi_script_name == /app/www//api/index.php
  • $request_filename == /app/www/index.php
4) And if you use $request_filename, you should set index using index directive, fastcgi_index will not work.
It means index index.php; in location