Nginx 404 для php

Nginx throws 404 only on php scripts using php-fpm

The server returns 404 on (and only on) .php scripts. I can rename them to .html and they’d be fine. How can I go about this?

user nginx; worker_processes 1; error_log /var/log/nginx/error.log; pid /run/nginx.pid; events < worker_connections 1024; >http < include /etc/nginx/mime.types; default_type application/octet-stream; log_format main '$remote_addr - $remote_user [$time_local] "$request" ' '$status $body_bytes_sent "$http_referer" ' '"$http_user_agent" "$http_x_forwarded_for"'; access_log /var/log/nginx/access.log main; sendfile on; keepalive_timeout 2; include /etc/nginx/conf.d/*.conf; index index.html index.htm; server < listen 80; server_name _; root /var/www/html; location / < root /var/www/html; index index.php index.html index.htm; >error_page 404 /404.html; location = /40x.html < #root /var/www/html; >error_page 500 502 503 504 /50x.html; location = /50x.html < #root /var/www/html; >location ~ \.php$ < root /var/www/html; try_files $uri =404; fastcgi_split_path_info ^(.+\.php)(/.+)$; fastcgi_pass unix:/var/run/php5-fpm.sock; fastcgi_index index.php; fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; include fastcgi_params; >> > 

4 Answers 4

Solved it. It turns out that the problem was the permissions set on the socket where php was listening. I just had to change a directive called listen.mode on /etc/php-fpm.d/www.conf

And set the user to nginx :

listen.owner = nginx listen.group = nginx 

So the file looks like this:

srwxr-x---. 1 nginx nginx 0 jul 8 08:59 /var/run/php5-fpm.sock 

Because I was using a unix socket instead of a tcp port:

listen = /var/run/php5-fpm.sock; 

Also, I was getting 404 instead of 500 or 503 because my www.conf was configured to redirect errors to custom pages, and since they weren’t there, I was getting 404 ‘s.

It appears that in most recent versions of the nginx distribution in Fedora (Fedora 22, 23), nginx uses the apache user by default, and the socket is set to the user apache too, so no further configuration is needed.

Right, you must control: — What user/group run nginx (or any webserver) — What user/group run php-fpm

I Actually got a «Not Found» error because a book I read gave me an incorrect matching string for the path /php_status which I had configured in php-fpm 7.0.x (currently 7.0.19) and in nginx 1.12 (currently 1.12.0)

Here is the /etc/php/7.0/fpm/pool.d/

pm.status_path = /php_status 

Here is the config for default in /etc/nginx/sites-available (I’m on Ubuntu)

server < listen 80 default; root /var/www; index index.html index.htm default.html; access_log /dev/null; error_log /dev/null; location / < try_files $uri $uri/ =404; >location /php_status < fastcgi_pass unix:/var/run/php7.0-fpm.sock; # fastcgi_pass 127.0.0.1:9000; fastcgi_param SCRIPT_FILENAME $fastcgi_script_name; include fastcgi_params; allow 127.0.0.1; deny all; >> 

Note: The following is designed so that /php_status is not publicly available on the internet (nor is PHP served or setup for default host). It also includes fastcgi_pass directive for tcp and unix-socket php-fpm

You also should run the following two commands after

sudo service nginx reload sudo service php7.0-fpm restart 
curl http://127.0.0.1/php_status 

Источник

Читайте также:  Css error text color

Ошибка 404 not found Nginx

Веб-серверы Nginx и Apache мало похожи друг на друга, и их отличия касаются не только особенностей подключения пользователей, но и обработки URL на сервере. Очень часто новые пользователи Nginx получают ошибку 404 для URL, которые, по сути, должны были бы работать.

В этой статье рассмотрим, почему возникает ошибка «404 not found Nginx», а также способы её устранения и отладки.Мы не будем разбираться с ситуацией, когда файла действительно нет на сервере — это решение, не требующее пояснений. Мы рассмотрим проблему обработки location в Nginx.

Почему возникает ошибка 404 в Nginx

Давайте сначала разберёмся, как обрабатываются URL в Nginx. Когда веб-сервер определил, к какому блоку server (сайту) нужно передать запрос пользователя, просматриваются все префиксные блоки location и выбирается тот, который подходит лучше всего. Например, рассмотрим стандартную конфигурацию для WordPress. Здесь префиксные location отмечены зелёным, а с регулярным выражением — оранжевым:

location /
index index.html index.php;
>
location /favicon.ico
access_log off;
>
location ~* \.(gif|jpg|png)$ expires 30d;
>
location ~ \.php$
fastcgi_pass localhost:9000;
fastcgi_param SCRIPT_FILENAME
$document_root$fastcgi_script_name;
include fastcgi_params;
>

Префиксные локейшены всегда начинаются с символа /. Регулярные же содержат символы регулярных выражений: ~ $ ^ * и так далее. Если пользователь запрашивает favicon.ico, то будет выбран второй location, так как он лучше всего соответствует запросу, при любом другом запросе будет выбран location /, так как он соответствует всем запросам, а других префиксных location у нас нет. Это просто, а дальше начинается магия. После того, как был найден нужный location, Nginx начинает проверять все регулярные выражения в порядке их следования в конфигурационном файле.

При первом же совпадении Nginx останавливает поиск и передаёт управление этому location. Или, если совпадений не было найдено, используется ранее обнаруженный префиксный location. Например, если запрос заканчивается на .php, то первый location будет проигнорирован, а управление передастся четвёртому (~ \.php$)

Таким образом, любое неверно составленное регулярное выражение в любой части конфигурационного файла может полностью всё сломать. Поэтому разработчики рекомендуют по минимум использовать регулярные выражения. Что касается вложенных location, то обрабатываются они так же как и основные, только уже после передачи управления в нужный location. Путём чтения конфигурационного файла понять, какой location вызывает 404 сложно, поэтому, чтобы исправить ошибку, нам понадобиться режим отладки Nginx.

Как включить режим отладки Nginx?

Сначала нам необходимо установить версию Nginx с поддержкой отладки. Чтобы проверить, поддерживает ли ваша текущая версия этот режим, наберите:

Читайте также:  Python requests query parameters

В выводе должна быть строчка «—with-debug». Если её нет, значит отладка не поддерживается, и надо установить версию с поддержкой. В CentOS такой пакет называется nginx-debug. Для его установки наберите:

sudo yum install nginx-debug

Теперь появился ещё один исполняемый файл, и он собран уже с поддержкой отладки:

Откройте конфигурационный файл вашего сайта или глобальный конфигурационный файл, если вы не задавали настройки логов отдельно для каждого сайта, и в конце стоки error_log замените error на debug:

error_log /var/log/nginx/domains/test.losst.pro.error.log debug

Останавливаем обычную версию и запускаем версию с отладкой:

Источник

Nginx — Customizing 404 page

Nginx+PHP (on fastCGI) works great for me. When I enter a path to a PHP file which doesn’t exist, instead of getting the default 404 error page (which comes for any invalid .html file), I simply get a «No input file specified.». How can I customize this 404 error page?

5 Answers 5

You can setup a custom error page for every location block in your nginx.conf, or a global error page for the site as a whole.

To redirect to a simple 404 not found page for a specific location:

You can append standard error codes together to have a single page for several types of errors:

To redirect to a totally different server, assuming you had an upstream server named server2 defined in your http section:

upstream server2 < server 10.0.0.1:80; >server < location /my_blog < error_page 404 @try_server2; >location @try_server2 < proxy_pass http://server2; >

The manual can give you more details, or you can search google for the terms nginx.conf and error_page for real life examples on the web.

Do you know if it’s possible to use a error wildcard? Something like error_page 50* = /error_50x.html; ?

Wildcards are not allowed — the wiki page for this server command is here wiki.nginx.org/NginxHttpCoreModule#error_page — also they aren’t necessary since the error codes are defined by the HTTP protocol which doesn’t change very often. See w3.org/Protocols/rfc2616/rfc2616-sec10.html or en.wikipedia.org/wiki/List_of_HTTP_status_codes for the complete list and I suppose add whatever numbers you like if you think there will be future codes needed.

Thanks. Currently I have 3 rules: /403.html , /404.html and /5xx.html , they all share the same root but somehow if I specify the location ~ /(?:40[34]|5xx)[.]html$ it will render the default nginx error pages, however, if I use a non-regex location it works. Do you have any idea why that happens?

That’s a separate issue too big to get into in these comments. I would make it a new question or just add the location entries. Link to the question if you make one and I will take a look.

Читайте также:  Java create random int

Источник

Nginx — Pass all 404 errors back to PHP-FPM for custom error page processing

I know this has been asked a thousand times, but all of the answers I’m found simply don’t work (for me or usually the original OP of those questions). So, I’ll try to explain the problem as best as I possibly can and hopefully we can get it working for me and for others who have asked before. My Nginx config (with lots of other irrelevant stuff removed) is as follows:

http < # Config from here removed server < listen 80; listen 443 ssl; server_name mydomain.co.uk; ssl_certificate /xxxxxxx.crt; ssl_certificate_key /xxxxxxx.key; # Custom error pages root /var/www/viovet_frontend; error_page 404 = /error404.php; # Any simple .php page location ~ \.php$ < root /var/www/xxxxxx; #index index.php index.html; include /etc/nginx/fastcgi.conf; fastcgi_pass phpfastcgiservers; include fastcgi_params; fastcgi_intercept_errors on; ># Lots more config and re-write rules here removed > upstream phpfastcgiservers < server xxxxx1:9001; server xxxxx2:9001; server xxxxx3:9001; fair; >> 
  • mydomain.co.uk/someNonExistantFile (didn’t match any location blocks)
  • mydomain.co.uk/someMissingFile.php (matched the .php file location block but the file doesn’t exist)

But they actually show the standard Nginx 404 page. If the location ~ \.php$ returns a different error code to 404 (e.g 5xx) then we don’t want to get involved, just return the content and headers that FastCGI returned in the first place.

I hope that makes sense and that someone can help. Thank you in advance.

EDIT: I have tried adding recursive_error_pages on; to the line after # Custom error pages but this actually causes all Nginx 404 Not Found errors to become Nginx 500 Internal Server Error errors.

EDIT: Adding other files: /etc/nginx/fastcgi.conf

fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; fastcgi_param QUERY_STRING $query_string; fastcgi_param REQUEST_METHOD $request_method; fastcgi_param CONTENT_TYPE $content_type; fastcgi_param CONTENT_LENGTH $content_length; fastcgi_param SCRIPT_NAME $fastcgi_script_name; fastcgi_param REQUEST_URI $request_uri; fastcgi_param DOCUMENT_URI $document_uri; fastcgi_param DOCUMENT_ROOT $document_root; fastcgi_param SERVER_PROTOCOL $server_protocol; fastcgi_param HTTPS $https if_not_empty; fastcgi_param GATEWAY_INTERFACE CGI/1.1; fastcgi_param SERVER_SOFTWARE nginx/$nginx_version; fastcgi_param REMOTE_ADDR $remote_addr; fastcgi_param REMOTE_PORT $remote_port; fastcgi_param SERVER_ADDR $server_addr; fastcgi_param SERVER_PORT $server_port; fastcgi_param SERVER_NAME $server_name; # PHP only, required if PHP was built with --enable-force-cgi-redirect fastcgi_param REDIRECT_STATUS 200; 

fastcgi_params

fastcgi_param QUERY_STRING $query_string; fastcgi_param REQUEST_METHOD $request_method; fastcgi_param CONTENT_TYPE $content_type; fastcgi_param CONTENT_LENGTH $content_length; fastcgi_param SCRIPT_NAME $fastcgi_script_name; fastcgi_param REQUEST_URI $request_uri; fastcgi_param DOCUMENT_URI $document_uri; fastcgi_param DOCUMENT_ROOT $document_root; fastcgi_param SERVER_PROTOCOL $server_protocol; fastcgi_param HTTPS $https if_not_empty; fastcgi_param GATEWAY_INTERFACE CGI/1.1; fastcgi_param SERVER_SOFTWARE nginx/$nginx_version; fastcgi_param REMOTE_ADDR $remote_addr; fastcgi_param REMOTE_PORT $remote_port; fastcgi_param SERVER_ADDR $server_addr; fastcgi_param SERVER_PORT $server_port; fastcgi_param SERVER_NAME $server_name; # PHP only, required if PHP was built with --enable-force-cgi-redirect fastcgi_param REDIRECT_STATUS 200; 

I guess I probably don’t need both of these anyway! 😉

Источник

Оцените статью