How to overwrite if a file is not found using NGINX

I am using NGINX on an Ubuntu server. I have this ghost:

server { listen 80; server_name *.example.com; root /home/nginx/vhosts/example.com/web; location / { index index.php; } location ~ \.php$ { fastcgi_pass 127.0.0.1:9001; fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; include /etc/nginx/fastcgi_params; } } 

I need to add a rule ...

If the file / directory is NOT FOUND, use index.php

How can I change the directive on server {}?

Thanks!

+6
source share
4 answers

You can use the try_files directive:

 try_files $uri $uri/ /index.php 

First it will try to find files and directories, and if that doesn't work, it will use index.php.

See also the front controller section of the nginx wiki.

+12
source

Ikke is correct, use try_files as follows:

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

But your PHP fastcgi location is unsafe. See this article to learn more about this.

For your setup you need to have something like this:

 location ~ \.php$ { try_files $uri /index.php; fastcgi_split_path_info ^(.+\.php)(/.+)$; include /etc/nginx/fastcgi_params; fastcgi_index index.php; fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; fastcgi_pass 127.0.0.1:9001; } 

Note that you must set the local fastcgi_param after enabling the global fastcgi_params configuration.

+3
source

You need to check the box:

 server { listen 80; server_name *.example.com; root /home/nginx/vhosts/example.com/web; location / { index index.php; } location ~ \.php$ { root /home/nginx/vhosts/example.com/web; fastcgi_pass 127.0.0.1:9001; fastcgi_index index.php; fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; include /etc/nginx/fastcgi_params; } } 

I hope, you

+2
source

I had the same problem on RH6 and EC2, and I fixed it with fastcgi_param $document_root in the fastcgi_param parameter. Hope this helps.

+1
source

Source: https://habr.com/ru/post/887506/


All Articles