no input file specified nginx php
Nginx+php-fpm (chroot). Из-за чего no input file specifed?
OS: Centos
PHP: 5.5.6
Nginx: 1.4.4
php-fpm pool config
drwxrwx— 8 example.ltd example.ltd 4096 Dec 2 11:57 example.ltd
ps aux | grep example.ltd
uid=500(example.ltd) gid=500(example.ltd) groups=500(example.ltd),499(nginx)
uid=498(nginx) gid=499(nginx) groups=499(nginx),500(example.ltd)
Unable to open primary script: /www/index.php (No such file or directory)
Так же пробовал изменения для виртуального хоста nginx найденный в интернете
Но ничего не помогает 🙁
Unable to open primary script: /index.php (No such file or directory)
nginx статику отдает хорошо
**что я делаю не так?**
read(6, »
\f\0QUERY_STRING\16\3REQUEST_METHODGET\f\0CONTENT_TYPE\16\0CONTENT_LENGTH\v\n
SCRIPT_NAME/index.php\v\n
REQUEST_URI/index.php\f\n
DOCUMENT_URI/index.php\r\31DOCUMENT_ROOT/srv/example.ltd/www\17\10SERVER_PROTOCOLHTTP/1.1\21\7GATEWAY_INTERFACECGI/1.1\17\vSERVER_SOFTWAREnginx/1.4.4\v\fREMOTE_ADDR93.84.53.238\v\5REMOTE_PORT32171\v\17SERVER_ADDR109.120.164.153\v\2SERVER_PORT80\v\20SERVER_NAMEexample.ltd\17\3REDIRECT_STATUS200\17\16SCRIPT_FILENAME/www/index.php\t\n
PATH_INFO/index.php\t\20HTTP_HOSTexample.ltd\17\n
HTTP_CONNECTIONkeep-alive\17hHTTP_USER_AGENTMozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.57 Safari/537.36\v\3HTTP_ACCEPT*/*\f!HTTP_REFERERhttp://example.ltd/index.php\24\21HTTP_ACCEPT_ENCODINGgzip,deflate,sdch\24 HTTP_ACCEPT_LANGUAGEru,en-US;q=0.8,en;q=0.6,be;q=0.4\v\200\0\0\353; _pk_id.1.869f=0372cc17b130d4ec.1377241318.29.1382802609.1382603499.; _pk_id.1.2f00=d658172cbb73d4a5.1382962602.2.1383147981.1382962814.\0\0\0″, 1024) = 1024
nginx конфиг в секции location
fastcgi_param SCRIPT_FILENAME /www$fastcgi_script_name;
а там уже видно будет, что он пытается открыть
Спасибо. но не помогло, или я не верно понял полученную информацию 🙂
read(6, »
\f\0QUERY_STRING\16\3REQUEST_METHODGET\f\0CONTENT_TYPE\16\0CONTENT_LENGTH\v\n
SCRIPT_NAME/index.php\v\n
REQUEST_URI/index.php\f\n
DOCUMENT_URI/index.php\r\31DOCUMENT_ROOT/srv/example.ltd/www\17\10SERVER_PROTOCOLHTTP/1.1\21\7GATEWAY_INTERFACECGI/1.1\17\vSERVER_SOFTWAREnginx/1.4.4\v\fREMOTE_ADDR93.84.53.238\v\5REMOTE_PORT32171\v\17SERVER_ADDR109.120.164.153\v\2SERVER_PORT80\v\20SERVER_NAMEexample.ltd\17\3REDIRECT_STATUS200\17\16SCRIPT_FILENAME/www/index.php\t\n
PATH_INFO/index.php\t\20HTTP_HOSTexample.ltd\17\n
HTTP_CONNECTIONkeep-alive\17hHTTP_USER_AGENTMozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.57 Safari/537.36\v\3HTTP_ACCEPT*/*\f!HTTP_REFERERhttp://example.ltd/index.php\24\21HTTP_ACCEPT_ENCODINGgzip,deflate,sdch\24 HTTP_ACCEPT_LANGUAGEru,en-US;q=0.8,en;q=0.6,be;q=0.4\v\200\0\0\353; _pk_id.1.869f=0372cc17b130d4ec.1377241318.29.1382802609.1382603499.; _pk_id.1.2f00=d658172cbb73d4a5.1382962602.2.1383147981.1382962814.\0\0\0″, 1024) = 1024
сначала смутило что DOCUMENT_ROOT с www а и SCRIPT_FILENAME тоже, убирал www из скрипта запроса, не помогло
потом cat php-fpm.strace | grep index.php
include fastcgi_params нужно вставлять самой первой строкой в требуемый location.
Пути в самом конфиге заданного pool нужно писать относительно chroot. Т.е. писать «fastcgi_param SCRIPT_NAME /www$fastcgi_script_name;» в контексте «root /srv/example.ltd/www;» неправильно.
strace лучше анализировать полный, т.е. без фильтрации определенных вызовов. Он гарантированно может показать, что и куда стучится и почему достучаться не может.
> Пути в самом конфиге заданного pool нужно писать относительно chroot. Т.е. писать «fastcgi_param SCRIPT_NAME /www$fastcgi_script_name;» в контексте «root /srv/example.ltd/www;» неправильно.
а тут путь к root, вроде как, отношения не имеет, более того он абсолютный
Добрый вечер, Ребята и Девчата.
Начал изучать Nginx и столкнулся со следующей проблемой, установил LEMP и решил протестировать работу php. Но получаю следующею ошибку No input file specified. при переходе на свой тестовый сервер http://192.168.56.101/info.php .
Вот мой конфиг файл /etc/nginx/nginx.conf:
Вот еще файл на всякий мой /etc/php-fpm.d/www.conf:
Вроде этого должно быть достаточно:
Не помогает, вот вывод ошибки при таком раскладе:
Starting nginx: nginx: [emerg] open() «/etc/nginx/snippets/fastcgi-php.conf» failed (2: No such file or directory) in /etc/nginx/nginx.conf:35
Дистрибутив какой? Версия Nginx какая?
Хотя нет, мне лень разбираться. Положи вот это:
в файл /etc/nginx/snippets/fastcgi-php-full.conf и замени include snippets/fastcgi-php.conf; на include snippets/fastcgi-php-full.conf;
Спасибо, я думаю это поможет тоже, но я нашел ошибку. В процессе установки я ставил себе задачу научиться собирать Nginx через компиляцию необходимых мне модулей, библиотек и я пользовался вот этим вот гайдом Compile and Install Nginx.
Прошу теперь мне помочь разобраться, как допустим пользователю nginx дать права на другие директории и нужно ли согласно гайда так делать. Можно ли пропустить этот шаг.
Я делаю все на CentOS7 и опыта у меня мало и конфиг файл пишу сам т.к. проще разобрать каждый контекст и директиву.
В этом есть какой-то сакральный смысл, или просто левая пятка захотела?
Да, кстати, вангую что у тебя не работает потому что нужно сделать
как в этой инструкции написано.
Ванга сегодня не зашла, я по этой делал инструкции)) И этот параметр выставлен и раскомменчен, в общем суть такая, у меня работает только если я создаю папки в /etc/nginx/. Если в любой другой типа /home/… то не работает. Тут дельный совет кто даст что чекнуть и что может влиять? Работаю под root.
В общем, как я и сказал, по тому гайду что я выше писал, для пользователя nginx домашний каталог изменен на /etc/nginx либо меняете в etc/passwd или оставляете, вот поэтому и не работало. Все, всем спасибо и пока!
В этом есть какой-то сакральный смысл, или просто левая пятка захотела?
Хочется человеку попердолиться на праздниках, тебе жалко что-ли?
Я не очень понял чего ты хочешь добиться, но на всякий случай замечу что в большинстве случаев не стоит держать в /home что-то связанное с nginx или другим подобным софтом. /home это для домашних директорий пользователей, тех которые из мяса и прочей требухи
не стоит держать в /home что-то связанное с nginx или другим подобным софтом
Не стоит, но довольно часто такие советы по установке «левого» софта можно встретить. Ту же кафку часто так ставят.
Советы применить патч бармина тоже не редко встречаются, это не повод. Для помойки вполне достаточно /usr/local и /opt
No input file specified when trying to run PHP #2
Comments
otaviosoares commented Sep 16, 2016
Hello, I might be doing something wrong but would like some help if possible.
I’m running this image with the php-fpm.
I’m able to view html pages but whenever I try to run a php file a get «No input file specified.».
The nginx error log:
2016/09/17 02:27:36 [error] 7#0: *55 FastCGI sent in stderr: «Unable to open primary script: /usr/share/nginx/html/index.php (No such file or directory)» while reading response header from upstream, client: 172.17.0.1, server: _, request: «GET /index.php HTTP/1.1», upstream: «fastcgi://172.17.0.5:9000», host: «localhost»
The text was updated successfully, but these errors were encountered:
We are unable to convert the task to an issue at this time. Please try again.
The issue was successfully created but we are unable to update the comment at this time.
matriphe commented Sep 17, 2016
Have you set the directory root correctly? Is the index.php exists? The
Nginx docker and the php-fpm container should have access to this root
directory.
Muhammad Zamroni
Sent with Airmail
On 17 September 2016 at 02.40.18, Otávio Augusto Soares (
notifications@github.com) wrote:
Hello, I might be doing something wrong but would like some help if
possible.
I’m running this image with the php-fpm.
I’m able to view html pages but whenever I try to run a php file a get «No
input file specified.».
How to Solve “No input file specified” with PHP and Nginx
“No input file specified” or “Primary script unknown” in the error log is one of the most frequently encountered issues in nginx+PHP.
People on serverfault and in the #nginx IRC channel asks for help with this so often that this post is mostly to allow me to be lazy and not have to type up the same answer every time.
This is actually an error from PHP and due to display_errors being 0ff people will often just get a blank page with no output. In a typical setup PHP will then send the error to stderr or stdout and nginx will pick up on it and log it in the nginx error log file. Thus people spend a ton of time trying to figure out why nginx isn’t working.
The root cause of the error is that PHP cannot find the file nginx is telling it to look for, and there are a few common cases that causes this.
Wrong Path Sent to PHP
The most common reason at the time of writing happens because a user uses a horrible tutorial found via google instead of actually understanding nginx. Reading my nginx primer will equip you to actually solve this on your own but since this post is actually dedicated to the error I’ll cheat this once and allow you to be lazy by just giving you the full solution.
This happens because nginx has 3 levels of inheritance commonly referred to as blocks, these being http, server and location, each being a sub-block of the parent. Directives in nginx inherit downwards but never up or across, so if you define something in one location block it will never be applied in any other location block under any circumstance.
The simple solution here is to just define the directive in your server block. (or http block even!) Generally the higher up your can define a directive the less duplicate directives you’ll need.
Incorrect File Permissions
Most people don’t really believe me when I tell them their file permissions are incorrect. They’re looking at the damn permissions and the PHP user can read the file just fine! Sadly, this shows a lack of understanding of Unix user permissions. Being able to read a file is not enough, a user must also be able to traverse to the file.
This effectively means that not only should the file have read permission, but the entire directory structure should have execute permission so that the PHP user can traverse the path. An example of this:
Say you have an index.php file in /var/www. /var/www/index.php must have read permission and both /var and /var/www must have execute permissions.
\.php$ then you will never use the fastcgi_index directive.
Chrooted Environment
If your PHP lives in a chrooted environment that nginx does not, then they basically have 2 different roots and the file path that nginx reports to PHP will not resolve to the actual file. A simple example to make this obvious:
Lets say you request phpinfo.php, nginx looks in your defined root and finds this file in: /home/user/public_html/phpinfo.php
The PHP process for user is chrooted to only have access to his directory for security reasons, so as far as PHP knows the root of the server is at /home/user. Therefore when nginx reports the file path PHP will look in: /home/user/home/user/public_html/phpinfo.php.
Either make sure both nginx and PHP has the same chroot or make sure you rewrite your internal URI before you fastcgi pass to PHP.
Open Basedir Restriction
PHP has the option to limit file access to certain directories defined in your php.ini. Some distributions might preconfigure this option for their packaging system.
SCRIPT_NAME Versus SCRIPT_FILENAME
Fastcgi has two parameters which are quite similiar in name, make sure that you’re not confusing the SCRIPT_NAME variable for the SCRIPT_FILENAME one. SCRIPT_FILENAME tells fastcgi the location of the script to execute while SCRIPT_NAME merely tells the name of the script.
NGINX vs PHP-FPM: No input file specified
NGINX PHP-FPM essentials
When you configure NGINX against PHP-FPM, what you really do is teach NGINX where is PHP-FPM listening and what kind of information has to be delivered to it.
NGINX does not do any processing of PHP scripts of its own. It merely talks to PHP-FPM and says:
and tell me what you see”.
In general, aside from some extra bits of information like environment variables, NGINX delivers one important piece of information to PHP-FPM – the filename of the script.
The standard bit of configuration illustrates it:
So this chmod in your site setup may be perfectly valid:
Note how NGINX has no access for index.php whatsoever, yet the page will work just fine in our setup.
Let’s expand to another case, our case of interest for this post.
This error is emitted by NGINX to the client’s browser. Because that’s what PHP-FPM happens to produce when you give it a filename that doesn’t exist.
Well, it’s a 404 error. Why bother? Sure enough, that’s not really the kind of error you want your users to see.
So in this post, I will tell you what are the dos and don’ts in fixing this error. That is, aside from obvious misconfiguration you might have.
Solution on the PHP-FPM side? None that I know
There’s no way to customize the message. Well, in theory, you can patch and recompile PHP like those poor folks who like to play with NGINX compilation.
So let’s move on to NGINX. There are multiple ways to solve it there, and I tell you this – there are too many ways to do things inherently wrong. Use the power that NGINX gives you wisely.
Solutions in NGINX
Going down from worst to best.
Worst
You may have seen this one:
You know why it’s already bad: if is evil. We all already know that blah blah.. Give me a break 🙂
rewrite or internal redirection cycle while internally redirecting to “/index.php
Well, I don’t want to if I can. There is never enough security. And secure chmod is something essential. Let’s keep trying.
So how about …
Stop right there. We’re still letting NGINX check file for existence, so it’s still going to fail if it has no access to the scripts in our secure setup.
Best solution
I owe you some explanation, right? In our location
Now NGINX doesn’t need to check for script existence. PHP-FPM will be the one to tell it.