N
N
NkDev2018-05-11 11:10:59
Nginx
NkDev, 2018-05-11 11:10:59

nginx. How to give 404 when accessing .php files?

The site structure is as follows:
/var/www/site/web
/var/www/site/src The index.php file, which is located in the web folder, is
used as a single entry point . All other php files of the project are located in src . When accessing any address in the browser that ends with .php (for example httр://site.ru/src/config.php or httр://site.ru/sdvasdfasfdasdf.php ), the error "500 Internal Server Error nginx" appears . How to make it so that instead of 500 a 404 page is given? My settings:


server {
    listen 80;
    server_name site.ru;
    root /var/www/site/web;
    index index.php;
    error_page 404 /404.php;

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

    location ~ \.php$ {
        try_files $uri = /404.php;
        fastcgi_index index.php;
        fastcgi_pass fpm:9000;
        fastcgi_param SCRIPT_FILENAME $request_filename;
        include fastcgi_params;
    }
}

In logs:
2018/05/11 08:17:20 [error] 5#5: *32 rewrite or internal redirection cycle while internally redirecting to "/404.php", client: 172.18.0.1, server: site.ru, request: "GET /src/config.php HTTP/2.0", host: "site.ru"
2018/05/11 08:18:49 [error] 5#5: *32 rewrite or internal redirection cycle while internally redirecting to "/404.php", client: 172.18.0.1, server: site.ru, request: "GET /sdvasdfasfdasdf.php HTTP/2.0", host: "site.ru"

Thank you!
UPDATE:
Partially worked after adding the following line:
location ~ \.php$ {
        root /var/www/site/src;
        ...
}

However, another problem appeared:
When accessing a non-existent file, for example htр://site.ru/sdvasdfasfdasdf.php , my 404 page appears - as expected.
But when accessing an existing file, for example htр://site.ru/config.php , the script is launched!
How can I prevent direct execution of php scripts from the browser located in the src folder ?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Alexey Hog, 2018-05-11
@Skiphog

Most likely the problem is in this line
. There is no such file, so there is a loop.
You need to either add a 404.php file to the root and process the error there, or change this line to
try_files $uri =404

P
Pavel, 2018-05-11
@PavelMonro

You need to look at the nxinx logs after calling php, and dance from there

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question