nginx error file not found solution


Using nginx+php as the webserver architecture model is widely used nowadays. However, the first step that needs to be realized is how to make nginx call php correctly. Because nginx calling php is not as straightforward as calling a static file, it requires dynamic execution of the php script. So it involves the configuration of the nginx.conf file.

When I was building wordpress and needed to build an lnmp environment, nginx reported an error: file not found and other errors. I found that my nginx configuration was wrong.

So the main content of this article will explain how to correctly configure the php calling method in nginx server, as well as the basic principles of configuration.

1. Modify nginx configuration file

1.1 Configuration file location

The default location of Nginx configuration file is: /etc/nginx/nginx.conf

In my environment nginx.conf is in /etc/nginx/nginx.conf

Profile analysis

# nginx运行的用户名
user nginx;
# nginx启动进程,通常设置成和cpu的数量相等,这里为自动
worker_processes auto;

# errorlog文件位置
error_log /var/log/nginx/error.log;
# pid文件地址,记录了nginx的pid,方便进程管理
pid /run/nginx.pid;

# Load dynamic modules. See /usr/share/nginx/README.dynamic.
# 用来加载其他动态模块的配置
include /usr/share/nginx/modules/*.conf;

# 工作模式和连接数上限
events {
    # 每个worker_processes的最大并发链接数
    # 并发总数:worker_processes*worker_connections
    worker_connections 1024;
}

# 与提供http服务相关的一些配置参数类似的还有mail
http {
    # 设置日志的格式
    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记录访问的用户、页面、浏览器、ip和其他的访问信息
    access_log  /var/log/nginx/access.log  main;

    # 这部分下面会单独解释
    # 设置nginx是否使用sendfile函数输出文件
    sendfile            on;
    # 数据包最大时发包(使用Nagle算法)
    tcp_nopush          on;
    # 立刻发送数据包(禁用Nagle算法)
    tcp_nodelay         on;
    # 链接超时时间
    keepalive_timeout   65;
    # 这个我也不清楚...
    types_hash_max_size 2048;

    # 引入文件扩展名与文件类型映射表
    include             /etc/nginx/mime.types;
    # 默认文件类型
    default_type        application/octet-stream;

    # Load modular configuration files from the /etc/nginx/conf.d directory.
    # See http://nginx.org/en/docs/ngx_core_module.html#include
    # for more information.
    include /etc/nginx/conf.d/*.conf;

    # http服务上支持若干虚拟主机。
    # 每个虚拟主机一个对应的server配置项
    # 配置项里面包含该虚拟主机相关的配置。
    server {
        # 端口
        listen       80 default_server;
        listen       [::]:80 default_server;
        # 访问的域名
        server_name  _;
        # 默认网站根目录(www目录)
        root         /usr/share/nginx/html;

        # Load configuration files for the default server block.

        include /etc/nginx/default.d/*.conf;

        # 默认请求
        location / {
        }

        # 错误页(404)
        error_page 404 /404.html;
            location = /40x.html {
        }

        # 错误页(50X)
        error_page 500 502 503 504 /50x.html;
            location = /50x.html {
        }
    }
}

Key points

  • 1. About error_log

The types of logs that can be set (what level of information is recorded) include: debug, info, notice, warn, error, and crit.

  • 2. About sendfile

The general network transmission process
is hard disk >> kernel buffer >> user buffer >> kernel socket buffer >> protocol stack.
After using sendfile,
the hard disk >> kernel buffer (fast copy to kernelsocket buffer) >> protocol stack
can significantly improve the transmission performance.

  • 3. tcp_nopush and tcp_nodelay

tcp_nopush only works when sendfile is enabled.
After tcp_nopush is enabled, the program will not send out immediately after receiving the data packet, but wait for the data packet to be sent out once when it is the largest, which can alleviate network congestion. (Nagleization)
On the contrary, tcp_nodelay sends the data packet immediately.

1.2 php fastcgi configuration

After analyzing the configuration file, start configuring the environment.

Because you only configure the PHP server and only use one port, you only need to change the server part.

Click 'i' in vim to enter edit mode

server {
        listen       80 default_server;
        listen       [::]:80 default_server;
        # 这里改动了,也可以写你的域名
        server_name  127.0.0.1;
        
        # 默认网站根目录(www目录)
        root         /var/www/;

        # Load configuration files for the default server block.
        include /etc/nginx/default.d/*.conf;

        location / {
            # 这里改动了 定义首页索引文件的名称
            index index.php index.html index.htm;
        }

        error_page 404 /404.html;
            location = /40x.html {
        }

        error_page 500 502 503 504 /50x.html;
            location = /50x.html {
        }

        # 这里新加的
        # PHP 脚本请求全部转发到 FastCGI处理. 使用FastCGI协议默认配置.
        # Fastcgi服务器和程序(PHP,Python)沟通的协议.
        location ~ \.php$ {
            # 设置监听端口
            fastcgi_pass   127.0.0.1:9000;
            # 设置nginx的默认首页文件(上面已经设置过了,可以删除)
            fastcgi_index  index.php;
            # 设置脚本文件请求的路径
            fastcgi_param  SCRIPT_FILENAME  $document_root$fastcgi_script_name;
            # 引入fastcgi的配置文件
            include        fastcgi_params;
        }
    }

After the modification is completed, switch the vim editor to the normal half mode (Esc), then enter: wq to save and exit.

Then restart the Nginx service

service nginx restart

The above configuration is successful, but the above configuration is only the nginx configuration part, and more content needs to be continued to learn.

1.3 Testing

We can determine whether the Nginx configuration is successful through the following method.

Create a php file in the root directory of Nginx website (/var/www/). I named it php_info.php casually.

The content is as follows:

<?php

    // 顺便可以看一下php的扩展全不全
    phpinfo();

Go to your website and see if you can open the file.
Your IP/file name, for example: 127.0.0.1/php_info.php

2. Operating principle of nginx+php

We have successfully configured it above, now let's take a look at the specific principles.

First, let’s briefly talk about the principle. The current mainstream nginx+php operating principle is as follows:

  • 1. The worker process of nginx directly manages each network request to nginx.

  • 2. For php, since php is a role of a cgi program in the whole network request process, a process management program named php-fpm is used to manage these requested php programs. The php-fpm program, like nginx, needs to listen on the port and have master and worker processes. The worker process directly manages each PHP process.

  • 3. About fastcgi: fastcgi is a process manager that manages cgi processes. There are many process managers on the market that implement fastcgi functions, and php-fpm is one of them. One more point, as a fast-cgi process management service, php-fpm will listen to the port, generally listens to port 9000 by default, and listens to the local machine, that is, only receives port requests from the local machine, so we usually enter the command netstat -nlpt|grep php-fpm will get:
    tcp 0 0 127.0.0.1:9000 0.0.0.0:* LISTEN 1057/php-fpm
    Here 127.0.0.1:9000 means listening to port 9000 of the machine.

  • 4. Regarding the fastcgi configuration file, the current fastcgi configuration file is generally placed in the same directory as nginx.conf. There are generally two types of configuration files: fastcgi.conf and fastcgi_params. Different nginx versions will have different configuration files. There is a very important difference between these two configuration files: the following configuration is missing in the fastcgi_parames file:
    fastcgi_param SCRIPT_FILENAME documentroot document_rootdocumentroo t fastcgi_script_name;
    We can open the fastcgi_parames file and add the above line, or we can add it dynamically where we want to use the configuration. Make this configuration take effect.

  • 5. When a PHP request needs to be processed, the worker process of nginx will hand over the request to the worker process of php-fpm for processing. That is to say, nginx calls PHP at the beginning. In fact, strictly speaking, nginx calls PHP indirectly.

After understanding the five simple principles above, configuring the PHP calling method in nginx becomes easy.

Configuration file details:

server {  
    listen       8011;  
    server_name  test.cn;  
    location ~ \.php?.*$ {  
        root           /share/test;  
        fastcgi_pass   127.0.0.1:9000;  
        fastcgi_param  SCRIPT_FILENAME  $document_root$fastcgi_script_name;  
        include        fastcgi_params;  
    }  
}  
  • 1. The first curly bracket server{ }: Needless to say, it represents an independent server.
  • 2. listen 8011: listens to port 8011 on behalf of the server
  • 3. location ~ .php?.*${ }: represents a location that can match the corresponding uri, used to match a type of uri, and do custom logic and configuration for the matched uri request. The location here matches all uri requests with .php, for example: http://192.168.244.128:8011/test.php/asdasd http://192.168.244.128:8011/index.php etc.
  • 4. root /share/test: Request the resource root directory and tell the uri matching the location to go to the /share/teset folder to find the resource with the same name.
  • 5. fastcgi_pass 127.0.0.1:9000: This line is the focus of this article: this line of code means that the uri request entering the location is regarded as a cgi program, and the request is sent to port 9000 and handed over to php -fpm processing.
  • 6、fastcgi_param SCRIPT_FILENAME d o c u m e n t r o o t document_root documentroo t fastcgi_script_name;: This line of configuration means: a line of fastcgi configuration is dynamically added. The configuration content is SCRIPT_FILENAME, which informs the management process of the cgi script name. Since there is only the fastcgi_params file in my nginx and no fastcgi.conf file, in order for php-fpm to know the specific value of SCRIPT_FILENAME, this line of configuration must be added dynamically.
  • 7. include fastcgi_params; Introduce fastcgi configuration file.
    The above is the simplest version of nginx to start the php script. After restarting nginx, create an xx.php file in the /share/test directory and enter <?php echo "hello world"; ?>Save, and then visit localhost:8011/xx.php in the browser to display hello world on the web page.

3. External network access intranet settings

External network IP: http://58.62.21.107:8382 maps the internal server IP 192.168.17.56 to port 82, that is: 192.168.17.56:82. You need to open port 82 in the nginx.conf configuration file for external network access, that is The following configuration:

[root@ceshi www]# cat /etc/nginx/nginx.conf
# For more information on configuration, see:
#   * Official English Documentation: http://nginx.org/en/docs/
#   * Official Russian Documentation: http://nginx.org/ru/docs/

user nginx;
worker_processes auto;
error_log /var/log/nginx/error.log;
pid /run/nginx.pid;

# Load dynamic modules. See /usr/share/nginx/README.dynamic.
include /usr/share/nginx/modules/*.conf;

events {
    worker_connections 1024;
}

http {
    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;
    tcp_nopush          on;
    tcp_nodelay         on;
    keepalive_timeout   65;
    types_hash_max_size 2048;

    include             /etc/nginx/mime.types;
    default_type        application/octet-stream;

    # Load modular configuration files from the /etc/nginx/conf.d directory.
    # See http://nginx.org/en/docs/ngx_core_module.html#include
    # for more information.
    include /etc/nginx/conf.d/*.conf;

    server {
        listen       82 default_server;   # 服务器端口,和外网映射的需保持一致
        listen       [::]:82 default_server; # 服务器端口,和外网映射的需保持一致
        server_name  192.168.17.56;
        root         /data/www/;

        # Load configuration files for the default server block.
        include /etc/nginx/default.d/*.conf;

        location / {
        }

        error_page 404 /404.html;
            location = /40x.html {
        }

        error_page 500 502 503 504 /50x.html;
            location = /50x.html {
        }


        # PHP 脚本请求全部转发到 FastCGI处理. 使用FastCGI协议默认配置.
        # Fastcgi服务器和程序(PHP,Python)沟通的协议.
        location ~ \.php$ {
            # 设置监听端口
            fastcgi_pass   127.0.0.1:9000;
            # 设置nginx的默认首页文件(上面已经设置过了,可以删除)
            fastcgi_index  index.php;
            # 设置脚本文件请求的路径
            fastcgi_param  SCRIPT_FILENAME  $document_root$fastcgi_script_name;
            # 引入fastcgi的配置文件
            include        fastcgi_params;
        }
    }

# Settings for a TLS enabled server.
#
#    server {
#        listen       443 ssl http2 default_server;
#        listen       [::]:443 ssl http2 default_server;
#        server_name  _;
#        root         /usr/share/nginx/html;
#
#        ssl_certificate "/etc/pki/nginx/server.crt";
#        ssl_certificate_key "/etc/pki/nginx/private/server.key";
#        ssl_session_cache shared:SSL:1m;
#        ssl_session_timeout  10m;
#        ssl_ciphers HIGH:!aNULL:!MD5;
#        ssl_prefer_server_ciphers on;
#
#        # Load configuration files for the default server block.
#        include /etc/nginx/default.d/*.conf;
#
#        location / {
#        }
#
#        error_page 404 /404.html;
#            location = /40x.html {
#        }
#
#        error_page 500 502 503 504 /50x.html;
#            location = /50x.html {
#        }
#    }

}

Guess you like

Origin blog.csdn.net/cljdsc/article/details/132768462