【Nginx和PHP教程(一)】安装、配置及初步使用

1. nginx基本介绍

2. nginx安装和环境配置

3. php基本介绍

4. php的安装和环境配置

5. JavaScript、php、html等的区别

6. ubuntu系统中php的安装和环境配置

1. nginx基本介绍 

Nginx(发音为“engine X”)是一款高性能的、轻量级的Web服务器软件,同时也是一款反向代理服务器和负载均衡器。Nginx的主要优点包括高性能、低资源占用、可靠性和灵活性。它已经成为一个广泛使用的Web服务器和反向代理服务器。

下面是Nginx的一些主要特点和功能:

  1. 高性能:Nginx的核心设计原则是为了提高性能和并发连接数。它可以同时处理数千个并发连接,使用少量的内存,这使得Nginx非常适合作为高流量的Web服务器和反向代理服务器。

  2. 反向代理:Nginx支持反向代理,可以通过代理缓存来提高Web应用程序的性能,同时也可以提供更好的安全性。

  3. 负载均衡:Nginx可以作为负载均衡器,它可以将请求转发到多个Web服务器,并确保请求的平衡分配。

  4. 静态内容服务:Nginx可以高效地提供静态内容服务,它可以直接将静态内容从磁盘中读取并返回给客户端,这使得Nginx在提供静态内容方面非常快速和高效。

  5. 可扩展性:Nginx的设计可以轻松地进行扩展,支持使用模块添加新的功能。

  6. 安全性:Nginx具有高度的安全性,可以抵御各种攻击,包括DDoS攻击、SQL注入攻击等。

  7. 轻量级:Nginx非常轻量级,占用资源很少,可以在低端硬件上运行,因此非常适合用于较小的项目。

总之,Nginx是一款高性能、可靠性强、安全性高、轻量级和灵活的Web服务器和反向代理服务器,是Web服务器中的佼佼者。

Nginx的历史可以追溯到2002年,当时Igor Sysoev在俄罗斯工作的一家ISP公司使用Apache作为Web服务器,但在面对高流量和高负载的情况下,他发现Apache的性能和可扩展性都有限。因此,他决定创建自己的Web服务器,这就是Nginx的雏形。

最初,Nginx是Igor Sysoev自己开发的,并在2004年首次发布。2008年,他辞职并创建了自己的公司,专注于开发和支持Nginx。目前,Nginx Inc.是一家专注于Web基础架构的软件公司,其核心产品是Nginx Web服务器和Nginx Plus。

Nginx是用C语言开发的,它的设计目标是为了高性能和可扩展性。Nginx的源代码是开放的,它遵循BSD许可证,因此可以免费使用和修改。在全球范围内,Nginx已经成为一个非常流行的Web服务器和反向代理服务器,许多知名的网站和公司都在使用Nginx,例如Netflix、Pinterest、GitHub、WordPress等等。

对于一名初级使用Nginx的人员,需要掌握以下基本知识:

  1. Nginx的基本概念和特性:初学者需要了解Nginx的基本概念,例如反向代理、负载均衡、静态文件服务、动态内容处理等等。还需要了解Nginx的一些基本特性,例如高性能、低资源占用、可扩展性和灵活性等等。

  2. Nginx的安装和配置:初学者需要了解如何安装Nginx,并进行基本的配置。这包括配置Nginx的服务器块、虚拟主机、SSL证书、反向代理等等。

  3. Nginx的日志管理:初学者需要了解如何配置和管理Nginx的访问日志和错误日志。这将帮助他们更好地了解Nginx的运行情况和问题。

  4. Nginx的性能优化:初学者需要了解如何通过调整Nginx的配置来提高其性能。这包括使用缓存、开启Gzip压缩、限制访问速率等等。

  5. Nginx的安全配置:初学者需要了解如何通过配置Nginx来保护Web应用程序的安全。这包括使用SSL证书、限制访问权限、防止DDoS攻击等等。

  6. Nginx的常用命令和工具:初学者需要了解如何使用常用的Nginx命令和工具来管理和调试Nginx,例如nginx -t、nginx -s reload、nginx -s stop、nginx -s quit等等。

总的来说,初学者需要了解Nginx的基本概念、安装和配置、日志管理、性能优化、安全配置以及常用命令和工具。这将帮助他们更好地使用和管理Nginx。

以下是与Nginx类似的一些软件:

  1. Apache:Apache是一个流行的开源Web服务器,也支持反向代理和负载平衡。与Nginx相比,Apache可以处理更多的并发请求,但它的性能通常比Nginx慢一些。

  2. Lighttpd:Lighttpd是另一个轻量级的Web服务器,类似于Nginx,它也具有高性能和低资源占用的特点。与Nginx相比,Lighttpd的配置相对简单,但其性能也不如Nginx。

  3. Caddy:Caddy是一个现代化的Web服务器和反向代理,类似于Nginx,它也具有高性能、低资源占用、可扩展性和灵活性等特点。与Nginx相比,Caddy的配置更加简单易用,但它的性能可能略低。

  4. HAProxy:HAProxy是一款高性能的负载平衡器和反向代理服务器,类似于Nginx,它可以将请求转发到多个Web服务器,并确保请求的平衡分配。与Nginx相比,HAProxy的配置相对复杂,但它也具有更高的性能和更多的高级功能。

总的来说,与Nginx类似的软件有很多,每个软件都有其独特的优点和缺点。选择合适的Web服务器和反向代理服务器取决于具体的应用需求和环境。

2. nginx的Centos/Ubuntu系统安装和环境配置

(1)Centos系统安装Nginx


sudo yum update              # Update the package repository

sudo yum install epel-release   # 默认情况下,CentOS存储库中没有Nginx软件包,需要添加Nginx存储库。

sudo yum install nginx       # Install Nginx

sudo systemctl start nginx   # Start the Nginx service

nginx -v                     # 验证Nginx安装

sudo systemctl status nginx  # Verify that Nginx is running

sudo systemctl enable nginx  # Enable Nginx to start at boot time

(2)Ubuntu安装Nginx


sudo apt update         # 1. 打开终端,使用sudo命令以管理员权限运行以下命令,更新软件包列表

sudo apt install nginx  # 2. 安装Nginx

# 3. 安装过程中,系统会要求你确认安装。按下Y键并按回车键继续安装。

sudo systemctl status nginx  # 4. 安装完成后,Nginx将自动启动。你可以使用以下命令检查Nginx的状态

配置Nginx

配置 Nginx 的基本步骤是:

1.创建新的服务器块:在 Nginx 配置文件中,您需要创建一个新的服务器块,它定义了 Nginx 如何处理 HTML 文件的请求。服务器块是一组配置指令,指定 Nginx 如何对特定域或 IP 地址的请求作出响应。Nginx 配置文件的路径通常为 /etc/nginx/nginx.conf

server {
    listen 80;
    root /var/www/html;         # 访问服务的根目录,建议用home路径
    index index.html;           # 访问ip默认显示的网页
    server_name example.com;    # 服务器的ip地址
}

或者用下面的格式,效果一样

    server {
        listen 80;
        server_name 123.456.68.118;   # 服务器ip地址

        location / {
            root /home/01_html;       # 指定的服务器根目录,注意不要选择root目录,一般用home目录
            index mainpage.html;      # 访问ip默认显示的网页,该网页需要置于上述根目录下
        }
}

注意:如果nginx监听端口443并启用SSL加密,则需要声明该服务器块对应的域名,SSL证书和私钥的位置等,可以直接参考 步骤9

2.指定监听地址和端口:listen 指令告诉 Nginx 在哪个 IP 地址和端口上监听传入请求。在上面的示例中,Nginx 监听端口 80 (HTTP)

3.指定根目录:root 指令告诉 Nginx 找到应该提供的文件的位置。在上面的示例中,Nginx 将在 /var/www/html 目录中查找文件。

4.指定默认文件:index 指令告诉 Nginx 当用户请求目录时应该提供哪个文件。在上面的示例中,Nginx 将提供 index.html 文件。

5.指定服务器名称:server_name 指令告诉 Nginx 此服务器块应该处理哪个域名或 IP 地址。

 添加上面部分的同时要把下面部分注释掉。

#server {
#    listen       80 default_server;
#    listen       [::]:80 default_server;
#    server_name  _;
#    root         /usr/share/nginx/html;
#
#    # 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 {
#    }
#}

6.保存配置文件:做出必要更改后,需要保存配置文件。

7.测试配置:可以通过运行 nginx -t 命令来检查配置是否正确。

[root@iZ2zehkhkwkx4pmvvjw2dlZ home]# nginx -t
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful

8.重新启动 Nginx:配置完成后,需要重新启动 Nginx 以应用更改。您可以使用命令 systemctl restart nginxservice nginx restart 来重新启动 Nginx。

systemctl restart nginx 或 service nginx restart

这些是配置 Nginx 以在云服务器上提供 HTML 文件的基本步骤。在 Nginx 配置文件中还有许多其他选项和设置,可用于自定义和优化 Nginx 的行为。

请注意,这些是一般步骤,根据您使用的 Nginx 版本、操作系统和配置方法,步骤和配置文件可能略有不同。

9.使用TLS协议和SSL证书(可选):SSL(Secure Sockets Layer)是一种安全协议,用于在客户端和服务器之间提供加密通信。TLS(Transport Layer Security)是SSL的后续版本,提供更强的安全和更好的性能。

下面这个配置文件定义了一个nginx服务器,它监听在443端口上,使用TLSv1.2和TLSv1.3协议进行安全通信。它的服务器名称是domain.com,使用/etc/nginx/keycrt/domain.com.crt/etc/nginx/keycrt/domain.com.key作为SSL证书和密钥(domain.com可以替换为自己对应的域名)。

server {
    listen 443 ssl;
    server_name domain.com;
    ssl_certificate /etc/nginx/key_crt/domain.com.crt;
    ssl_certificate_key /etc/nginx/key_crt/domain.com.key;
    ssl_protocols TLSv1.2 TLSv1.3;

    location / {
        root /home/01_directory;
        index mainpage.html;
    }

    location ~ \.php$ {
        root /home/01_directory;
        try_files $uri =404;
        fastcgi_pass unix:/var/run/php-fpm/www.sock;
        fastcgi_index index.php;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        include fastcgi_params;
    }
}

这个服务器有四个location块,每个块都定义了不同的URL路径和处理方式。第一个location块处理根路径/,将请求映射到/home/01_directory目录下的mainpage.html文件。第二个location块处理/home/01_directory路径,将请求代理到本地地址127.0.0.1:10087。第三个location块处理/node路径,将请求代理到本地地址127.0.0.1:3000,并设置了一些代理头。最后一个location块处理以.php结尾的请求,将请求映射到/home/01_directory目录下的对应文件,并使用fastcgipass指令将请求代理到PHP-FPM进程。

10. 报错分析1

如果访问ip出现了403 forbidden error,大概率是nginx没有目录和文件权限,执行以下命令:

You can run the following command to change the owner of the directory to nginx user:

sudo chown -R nginx:nginx /root/01_sun789/02_nginx/01_html

You should also verify the permission of the folder, The folder should be 755.

sudo chmod 755 /root/01_sun789/02_nginx/01_html

将上述 /root/01_sun789/02_nginx/01_html目录改为自己文件的对应目录

After that, you need to restart the Nginx service for the changes to take effect:

sudo systemctl restart nginx

注意不要将文件放在root目录下面,上面是将目录放在了root下面,所以访问权限总是有问题。

You can also check the status of the service using the command:

sudo systemctl status nginx

To stop using Nginx, you would need to stop the Nginx service on your server.

sudo systemctl stop nginx

To start the Nginx service on your server, you can use the command start or restart instead of stop command that I mentioned earlier.

sudo systemctl start nginx

9. 报错分析2

如果文件所有者和用户组都已经设置为nginx,但nginx仍然无法访问该文件,可能是由于SELinux策略阻止了nginx访问该文件。默认情况下,SELinux会限制Web服务器访问用户主目录下的文件。这是为了保护系统安全,避免Web服务器被攻击者利用来访问敏感文件。经测试,阿里云默认是不开启的,digitalocean云服务器是默认开启的。

您可以使用以下命令来检查SELinux的状态:

sestatus

如果SELinux状态为“Enforcing”,则表示SELinux策略正在执行。

要允许Web服务器访问用户主目录下的文件,您需要将SELinux策略设置为允许这样的访问。您可以使用以下命令来设置SELinux策略:

sudo setsebool -P httpd_read_user_content 1

该命令将允许Web服务器读取用户主目录下的文件。请注意,-P选项将设置永久性策略,即使系统重新启动,策略也会保持不变。

也可以通过修改/etc/selinux目录下的confgi配置文件来关闭selinux,修改之后需要重启系统来生效。尤其是针对digitalocean的云服务器。

reboot

如果您仍然无法通过IP地址访问文件,则可能还需要检查防火墙配置以确保端口已打开。

SELinux(Security-Enhanced Linux)是一种安全增强技术,它在Linux内核中实现了强制访问控制(MAC)机制。它可以对进程、文件、网络端口等资源进行细粒度的访问控制,从而提供了更高的安全性,可以有效地防止系统被攻击者入侵、病毒或恶意软件感染等安全威胁。

SELinux的实现是通过在Linux内核中添加了一个安全模块,该模块使用安全策略来控制系统中不同组件之间的交互。这些策略是基于规则的,可以根据需要进行定制,以适应特定的安全环境和需求。

SELinux在Linux发行版中已经成为标准的安全增强技术,并且被广泛应用于各种场合,如服务器、工业控制系统、网络设备等。它可以提供可靠的安全保障,从而保护系统和数据免受攻击和滥用。

3. php基本介绍 

PHP是一种开源服务器端脚本语言,最初由Rasmus Lerdorf于1995年开发,后被多人维护和发展。以下是关于PHP的详细介绍:

发展历程 PHP最初是一种简单的网页表单处理脚本语言,用于处理表单提交的数据并生成HTML页面。随着时间的推移,PHP不断发展壮大,增加了更多的特性和功能。PHP 3于1998年发布,是第一个真正可用于Web开发的版本。PHP 4在2000年发布,增加了更多的特性和性能改进。PHP 5于2004年发布,引入了面向对象编程和一些其他的重大变化。PHP 7于2015年发布,引入了一些重大的性能改进和新特性。

特点 PHP的最大特点是其易于学习和使用。它是一种动态类型语言,使得编写代码变得更加简单和快速。PHP的语法类似于C语言,易于学习和理解。PHP也是一种跨平台语言,可在多种操作系统上运行。PHP的另一个优点是其广泛的社区支持,这意味着可以轻松地找到大量的文档、教程和开发工具。

功能 PHP是一种用于Web开发的脚本语言,具有许多功能,例如:

  • 生成动态Web页面;
  • 处理Web表单数据;
  • 连接到数据库,并执行查询和更新操作;
  • 加密数据和创建哈希;
  • 创建和操作文件;
  • 发送电子邮件;
  • 处理图像和其他媒体文件;
  • 管理会话和Cookie;
  • 进行XML解析和生成;
  • 处理HTTP请求和响应。

用途 PHP通常用于服务器端Web开发,包括构建Web应用程序、Web服务、CMS、博客、论坛等等。许多流行的Web框架,如Laravel、Symfony和CodeIgniter,都是用PHP编写的。PHP也可以用于命令行脚本、系统管理和其他一些用途。

开发语言 PHP本身是用C语言开发的,因此它的底层代码是用C语言编写的。PHP代码本身可以在任何文本编辑器中编写,也可以使用集成开发环境(IDE)来提高开发效率。常用的PHP开发工具包括Eclipse、NetBeans和PHPStorm。

作为一个初学者,想要掌握PHP,需要掌握以下知识和技能:

  1. 基础语法和语言结构:了解PHP的基本语法、掌握变量、运算符、条件语句、循环结构、数组、函数等基本语言结构。

  2. 数据库操作:学会使用PHP连接数据库、执行查询和更新操作、使用PDO等数据库操作工具。

  3. Web开发基础:了解Web开发的基础知识,如HTTP协议、HTML、CSS、JavaScript等。

  4. 服务器环境:熟悉Web服务器的基本知识、了解PHP在Web服务器上的运行原理,如Apache、Nginx等。

  5. 框架:学习使用PHP框架来加速开发,如Laravel、Symfony等。

  6. 安全性:了解Web应用程序的安全问题,如SQL注入、跨站脚本攻击等,并学习如何防止这些攻击。

  7. 调试和错误处理:学习使用调试工具和技术来解决代码中的错误和问题,如Xdebug等。

  8. 版本控制:学习使用版本控制系统,如Git等,以便更好地管理代码和协作开发。

除了以上内容,初学者还需要多做实践,编写简单的PHP程序来巩固所学知识,并不断提高自己的编程能力。同时,阅读PHP相关的书籍、教程、文档、论坛等资料也能够帮助初学者快速掌握PHP。

4. php的安装和环境配置

Here's a step-by-step guide to install and configure PHP on your CentOS cloud server:

1. 首先,更新 CentOS 系统以获取最新的软件包列表:

sudo yum update

查看 CentOS 系统中可用的 PHP 软件包版本列表。该命令将会列出所有已经安装或可用的 PHP 软件包及其版本号。 

yum list php

2. 运行以下命令以安装 PHP 和必需的扩展:

sudo yum install php php-fpm php-mysqlnd php-gd php-mbstring

这个命令是用于在 CentOS 或 Red Hat 系统上安装 PHP 及其相关组件的。

具体而言,该命令会使用 YUM 包管理器,安装以下 PHP 组件:

  • php:PHP 语言核心库
  • php-fpm:PHP FastCGI 进程管理器,用于管理 PHP 进程池
  • php-mysqlnd:PHP MySQL 数据库驱动程序
  • php-gd:PHP 图形处理库,用于处理图像
  • php-mbstring:PHP 多字节字符串扩展,提供了对多字节字符集的支持

通过这个命令安装这些组件后,就可以在服务器上运行 PHP 应用程序并与 MySQL 数据库进行交互,并且可以处理图像和多字节字符串。

3. 运行以下命令以启动 PHP-FPM 服务,并确保该服务在系统启动时自动启动:

sudo systemctl start php-fpm
sudo systemctl enable php-fpm

4. 配置 PHP-FPM

PHP-FPM(FastCGI Process Manager)是一个用于管理 PHP 进程的工具。在 CentOS 中,PHP-FPM 的配置文件位于 /etc/php-fpm.d/www.conf

打开该文件并进行以下更改:

sudo nano /etc/php-fpm.d/www.conf

5. 将 usergroup 设置为 Nginx 用户和组:

user = nginx
group = nginx
listen.owner = nginx
listen.group = nginx
  • Save and close the file.

6. Next, open the Nginx configuration file for your website:

配置 Nginx:在您的 Nginx 配置文件中,找到 location 指令的 PHP 部分。对其更改:

sudo nano /etc/nginx/conf.d/yourwebsite.conf

或者修改 /etc/nginx/nginx.conf 路径下的 nginx.conf 也是可以的,因为

When you add a server block directly into the nginx.conf file instead of creating a separate configuration file under /etc/nginx/conf.d/, the server block will still be processed by Nginx as long as it is included in the http context.

However, it is generally not recommended to edit the nginx.conf file directly, as it may lead to issues with future upgrades and maintenance. It is best practice to use separate configuration files under /etc/nginx/conf.d/ to keep your configuration organized and easy to manage.

Additionally, having a separate configuration file for each virtual host allows for better isolation of each host's configuration, making it easier to troubleshoot issues and make changes without affecting other hosts.

  • Add the following lines within the server block to handle PHP files with PHP-FPM:(注意根目录root必不可少,注意核对/var/run/php-fpm/www.sock路径,如果该路径下不存在www.sock文件,需要在PHP-FPM配置文件中找到listen选项,然后listen值作为fastcgi_pass。如果该路径下存在www.sock文件,可以在按照如下语法在nginx配置文件中进行location添加。注意:即使服务器开启了https,php在配置文件中的location也可以参考如下代码来写。


location ~ \.php$ {
root /home/01_html;
try_files $uri =404;
fastcgi_pass unix:/var/run/php-fpm/www.sock;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
include fastcgi_params;
}

 该配置告诉 Nginx 通过 FastCGI 协议将请求发送到 PHP-FPM 进程,然后将响应返回给客户端。 

  • Save and close the file.

一个参考案例为

    server {
        listen 80;
        server_name 37.111.67.118;

        location / {
            root /home/01_html;
            index main.html;
        }

        location /about {
            root /home/01html;
            index about.html;
        }

        location ~ \.php$ {
            root /home/01_html;
            try_files $uri =404;
            fastcgi_pass unix:/var/run/php-fpm/www.sock;
            fastcgi_index index.php;
            fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
            include fastcgi_params;
    }

    }

关于上述nginx配置文件中location关键词的含义

在Nginx的配置文件中,location是一个指令,用于指定请求的URL应该如何被处理。它可以被用于匹配不同的URL,并在不同的情况下使用不同的处理方式。

在上述Nginx配置文件中,有三个不同的location块:

  1. 第一个location块指定了根路径/的处理方式。它将请求的URL映射到/home/01_html目录下的文件,并使用main.html作为默认文件名。这意味着,当用户请求http://37.111.67.118/时,Nginx会返回/home/01_html/main.html文件的内容。

  2. 第二个location块指定了/about路径的处理方式。它与第一个location块类似,但是将请求的URL映射到/home/01html目录下的about.html文件。这意味着,当用户请求http://37.111.67.118/about时,Nginx会返回/home/01html/about.html文件的内容。

  3. 第三个location块使用了正则表达式,指定了以.php结尾的URL的处理方式。它将请求的URL映射到/home/01_html目录下的PHP文件,并使用FastCGI协议将请求转发给PHP-FPM处理。这意味着,当用户请求http://37.111.67.118/test.php时,Nginx会将请求转发给PHP-FPM处理,并将/home/01_html/test.php文件的内容返回给用户。

总之,location关键字允许Nginx根据请求的URL匹配不同的处理方式,从而实现URL的路由和请求的处理。

如果上述PHP-FPM配置文件中找到listen选项中有www.sock,则不需要再看接下来的部分,直接跳到步骤7进行测试和重启即可。


下面是一个没有www.sock文件的示例,在PHP-FPM配置文件(路径/etc/php-fpm.d/www.conf)中找到listen选项如下所示,

The address on which to accept FastCGI requests.
; Valid syntaxes are:
; 'ip.add.re.ss:port' - to listen on a TCP socket to a specific address on
; a specific port;
; 'port' - to listen on a TCP socket to all addresses on a
; specific port;
; '/path/to/unix/socket' - to listen on a unix socket.
; Note: This value is mandatory.
listen = 127.0.0.1:9000

可以确认在PHP-FPM配置文件中,listen选项的值为127.0.0.1:9000,这意味着PHP-FPM将会监听在127.0.0.19000端口上,而不是使用Unix域套接字文件。

因此,在Nginx配置文件中,应该使用fastcgi_pass指定127.0.0.1:9000作为PHP-FPM的后端地址,而不是使用Unix域套接字文件路径。例如:

location ~ \.php$ {
    fastcgi_pass   127.0.0.1:9000;
    fastcgi_index  index.php;
    fastcgi_param  SCRIPT_FILENAME  $document_root$fastcgi_script_name;
    include        fastcgi_params;
}

如果您想要使用Unix域套接字文件来与PHP-FPM通信,需要在PHP-FPM配置文件中将listen选项的值设为Unix域套接字文件的路径(例如/var/run/php-fpm/php-fpm.sock),并在Nginx配置文件中将fastcgi_pass指定为该路径。

小知识 

在Nginx和PHP-FPM之间通信时,可以使用TCP socket或Unix域套接字文件两种方式。

使用TCP socket(例如127.0.0.1:9000)的优点是:

  • 可以跨越不同的机器和网络进行通信。
  • 可以通过防火墙和网络设备进行配置和限制。

使用Unix域套接字文件(例如/run/php-fpm/www.sock)的优点是:

  • 比TCP socket更快更高效,因为它不需要进行网络通信。
  • 更安全,因为Unix域套接字文件只能被本地进程访问,而不是通过网络进行访问。

在实际应用中,使用哪种方式取决于具体的场景和需求。如果Nginx和PHP-FPM运行在同一台机器上,使用Unix域套接字文件通常更为常见和推荐。如果需要跨越不同的机器和网络进行通信,或者需要通过防火墙和网络设备进行配置和限制,则应该使用TCP socket。

无论使用TCP socket还是Unix域套接字文件,在Nginx配置文件中使用fastcgi_pass指定正确的后端地址即可。

7. 测试和重启

  • Test Nginx configuration:

sudo nginx -t
  • Restart Nginx:
sudo systemctl restart nginx
  • 重启PHP-FPM
systemctl restart php-fpm

8. Finally, create a test PHP file to confirm the setup:

为了测试 PHP 是否已正确安装并配置,您可以在网站根目录中创建一个 phpinfo.php 文件。该文件包含以下代码:

sudo nano /usr/share/nginx/html/info.php
  • Add the following content to the file:
<?php
phpinfo();

访问 http://your-server-address/phpinfo.php 以查看 PHP 信息。

如果 PHP 成功安装并配置,则应该能够在浏览器中看到 PHP 的版本和相关信息。

以上是在 CentOS 中安装 PHP 的基本步骤。请注意,这仅涵盖了基础安装和配置,您可能需要根据您的需求进行进一步配置和优化。

上述这段 PHP 代码的含义是输出当前 PHP 环境的详细信息phpinfo()PHP 内置的函数,它将会输出 PHP 运行时的配置信息,包括 PHP 版本、操作系统信息、PHP 配置信息、已加载的扩展信息、环境变量等。

当在 Web 服务器上运行该代码时,将会输出一个包含 PHP 环境信息的页面,通常可以通过浏览器访问这个页面。这对于了解 PHP 环境配置和调试 PHP 应用程序非常有帮助。但是请注意,在生产环境中,建议不要将 phpinfo() 函数输出的信息公开,以避免信息泄露和安全问题。

9. 如果云服务器开启了https,安装php的过程同上,只需要在nginx的配置文件中添加如下代码块即可。

location ~ \.php$ {
root /home/01_html;
try_files $uri =404;
fastcgi_pass unix:/var/run/php-fpm/www.sock;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
include fastcgi_params;
}

以下是注意事项:

1. 如果涉及到php对文本的写入,则需要修改相应文本权限,如下

以下是数字形式的权限对应的列表:

- 777 对应 rwxrwxrwx
- 776 对应 rwxrwxr--
- 775 对应 rwxrwxr-x
- 774 对应 rwxrwxr--
- 766 对应 rwxrw-rw-
- 765 对应 rwxrw-r-x
- 764 对应 rwxrw-r--
- 755 对应 rwxr-xr-x
- 754 对应 rwxr-xr--
- 744 对应 rwxr--r--
- 666 对应 rw-rw-rw-
- 664 对应 rw-rw-r--
- 644 对应 rw-r--r--
- 600 对应 rw-------
- 500 对应 r-x------
- 400 对应 r--------
- 000 对应 ---------

其中,每个数字都代表了一个权限组,每个权限组包括三个数字,分别代表了文件拥有者、文件所属组以及其他用户的权限。

第一个数字表示拥有者的权限,第二个数字表示所属组的权限,第三个数字表示其他用户的权限。其中,数字1表示有权限,数字0表示没有权限。

例如,数字表示为666的权限,对应的权限字符串为rw-rw-rw-,其中r表示读权限,w表示写权限,-表示没有权限。这表示文件拥有者、文件所属组以及其他用户都有读写权限。

请注意,数字权限和符号权限的使用可能因操作系统和文件系统而有所不同。因此,建议在特定操作系统和文件系统环境下查看相关文档以获取更准确的信息。

例如,您需要检查questiondata.txt文件的权限和所有权,确保PHP进程有足够的权限访问该文件。您可以使用以下命令修改文件的权限:

sudo chmod 666 /home/01_html/questiondata.txt

2. 通过查看PHP的日志文件可以帮助您排查PHP脚本无法写入文件的问题。

在PHP脚本中,可以使用error_log()函数将错误消息写入到PHP的错误日志文件中。默认情况下,PHP的错误日志文件位置可能会因不同的操作系统和PHP版本而有所不同。以下是一些可能的位置:

  • /var/log/php_errors.log
  • /var/log/httpd/error_log
  • /var/log/nginx/error.log
  • /usr/local/php/var/log/php-fpm.log

3. 如运行过程中出现与json_encode function有关的报错,则需要安装json扩展,如下

sudo yum install php-json

 然后重启nginx即可。

4. 如果运行过程中出现下面报错信息,提示web 服务器用户没有相关目录或文件的权限

2023/02/13 10:23:03 [error] 161944#0: *176 FastCGI sent in stderr: "PHP message: PHP Warning: session_start(): open(/var/lib/php/session/sess_mtg3r9bodv5j299pbehut4u1e1, O_RDWR) failed: Permission denied (13) in /home/01_html/login.php on line 3 PHP message: PHP Warning: session_start(): Failed to read session data: files (path: /var/lib/php/session) in /home/01_html/login.php on line 3 PHP message: PHP Notice: Undefined index: loggedin in /home/01_html/login.php on line 28" while reading response header from upstream, client: 218.247.135.26, server: 391.101.68.118, request: "GET /login.php HTTP/1.1", upstream: "fastcgi://unix:/var/run/php-fpm/www.sock:", host: "391.101.68.118", referrer: "http://391.101.68.118/login.php"

输入以下命令,调整session目录的权限,然后重启nginx服务器即可 

sudo chown -R nginx:nginx /var/lib/php/session

参考资料解决:centos8+php7.2下安装composer提示:The json extension is missing._୧⍢⃝୨ LonelyCoder的博客-CSDN博客_the json extension

5. 程序运行遇到问题的可能原因:

1. 配置文件中的参数未设置或者设置错误。

比如:php.ini配置文件通常位于 /etc/php.ini目录下面

          nginx服务器的error.log位于 /var/log/nginx/error.log

2. 缺少相关函数的库,需要安装相应库。

3. 程序缺少对某些目录的读取或者写入权限。

  如改变目录的用户权限:

sudo chown -R nginx:nginx /var/lib/php/session

一般来说,利用php在web端向服务器端中的文件写入数据时,一定要记得更改文件权限,否则无法写入。

为了更高效地解决上述问题,第一时间应该去查看nginx服务器的error.log。

下面是使用php创建的云端笔记小程序。

示例1: 

<!DOCTYPE html>
<html>
<head>
  <title>Write to File</title>
  <style>
    form {
      display: flex;
      flex-direction: column;
      align-items: center;
    }

    textarea[readonly] {
      display: block;
      margin: 0 auto;
      text-align: center;
    }
  </style>
</head>
<body>
<h1>Write to File</h1>
<form action="infoo.php" method="post">
  <p><label for="data">Enter Data:</label></p>
  <textarea rows="16" cols="100" id="data" name="data"></textarea><br><br>
  <input type="submit" value="Submit">
</form>

<br><br>
<form action="infoo.php" method="get">
  <input type="submit" value="Display Latest Content" name="display_content">
</form>
<?php
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
  date_default_timezone_set("Asia/Shanghai");
  $data = "[" . date("Y-m-d H:i:s") . "]\n" . $_POST['data'];
  $file = fopen("data.txt", "a");
  fwrite($file, "\n" . $data . "\n");
  fclose($file);
} else if ($_SERVER['REQUEST_METHOD'] === 'GET' && isset($_GET['display_content'])) {
  $file = fopen("data.txt", "r");
  $content = fread($file, filesize("data.txt"));
  fclose($file);
  echo "<br><br><textarea rows='24' cols='100' readonly>" . $content . "</textarea>";
}
?>
</body>
</html>

 示例2: 

<!DOCTYPE html>
<html>
<head>
  <title>Write to File</title>
  <style>
    form {
      display: flex;
      flex-direction: column;
      align-items: center;
    }
 
    textarea[readonly] {
      display: block;
      margin: 0 auto;
      text-align: center;
    }
 
    .unshow-container {
      text-align: center;
      margin-top: 20px;
    }
  </style>
  <script>
    function toggleVisibility() {
      const textarea = document.querySelector("textarea[readonly]");
      textarea.style.display = textarea.style.display === "block" ? "none" : "block";
    }
  </script>
</head>
<body>
<h1>Write to File</h1>
<form action="infoo.php" method="post">
  <p><label for="data">Enter Data:</label></p>
  <textarea rows="16" cols="100" id="data" name="data"></textarea><br><br>
  <input type="submit" value="Submit">
</form>
 
<br><br>
<form action="infoo.php" method="get">
  <input type="submit" value="Display Latest Content" name="display_content">
</form>
<div class="unshow-container">
  <input type="button" value="Unshow" onclick="toggleVisibility()">
</div>
<?php
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
  date_default_timezone_set("Asia/Shanghai");
  $data = "[" . date("Y-m-d H:i:s") . "]\n" . $_POST['data'];
  $file = fopen("data.txt", "a");
  fwrite($file, "\n" . $data . "\n");
  fclose($file);
} else if ($_SERVER['REQUEST_METHOD'] === 'GET' && isset($_GET['display_content'])) {
  $file = fopen("data.txt", "r");
  $content = fread($file, filesize("data.txt"));
  fclose($file);
  echo "<br><br><textarea rows='24' cols='100' readonly>" . $content . "</textarea>";
}
?>
</body>
</html>

示例3:

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>Write to File</title>
  <style>
    form {
      display: flex;
      flex-direction: column;
      align-items: center;
    }
 
    textarea[readonly] {
      display: block;
      margin: 0 auto;
      text-align: center;
    }
 
    .unshow-container {
      text-align: center;
      margin-top: 20px;
    }
  </style>
  <script>
    function toggleVisibility() {
      window.location.href = "http://39.101.68.118/infoo.php";
    }
  </script>
</head>
<body>
<h3>Write to File</h3>
<form action="infoo.php" method="post">
  <p><label for="data">Enter Data:</label></p>
  <textarea rows="16" cols="100" id="data" name="data"></textarea><br><br>
  <input type="submit" value="Submit">
</form>
 
<br><br>
<form action="infoo.php" method="get">
  <input type="submit" value="Display Latest Content" name="display_content">
</form>
<div class="unshow-container">
  <input type="button" value="Unshow" onclick="toggleVisibility()">
</div>
<?php
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
  date_default_timezone_set("Asia/Shanghai");
  $data = "[" . date("Y-m-d H:i:s") . "]\n" . $_POST['data'];
  $file = fopen("data.txt", "a");
  fwrite($file, "\n" . $data . "\n");
  fclose($file);
} else if ($_SERVER['REQUEST_METHOD'] === 'GET' && isset($_GET['display_content'])) {
  $file = fopen("data.txt", "r");
  $content = fread($file, filesize("data.txt"));
  fclose($file);
  echo "<br><br><textarea rows='24' cols='100' readonly>" . $content . "</textarea>";
}
?>
</body>
</html>

5. JavaScript、php、html等的区别

JavaScript, PHP, HTML, and CSS are all essential technologies used in web development. Here's a quick comparison:

JavaScript:

  • It is a client-side scripting language used for creating dynamic and interactive web pages.
  • It is an object-oriented language and supports event-driven programming.
  • It can be used for server-side development as well with Node.js.

PHP:

  • It is a server-side scripting language used for developing dynamic websites and web applications.
  • It is an interpreted language and can be easily embedded in HTML.
  • It is widely used for server-side tasks such as reading and writing to databases, processing form data, and generating dynamic content.

HTML:

  • It is a markup language used for creating web pages and specifying the structure and content of a web page.
  • It uses tags to define the structure of the page, such as headings, paragraphs, images, links, and more.

CSS:

  • It is a stylesheet language used to style and layout HTML pages.
  • It provides a way to separate presentation and content, making it easier to maintain the look and feel of a website.
  • It can be used to control things such as font, color, spacing, and layout of elements on a web page.

Commonalities:

  • All four technologies are essential for creating modern websites.
  • HTML provides the structure and content of a web page, CSS provides the styling, JavaScript provides interactivity, and PHP is used for server-side processing.
  • They can all be used together to create dynamic, interactive, and aesthetically pleasing websites.

Differences:

  • JavaScript and PHP are programming languages, while HTML and CSS are markup and styling languages, respectively.
  • JavaScript is primarily used for client-side scripting, while PHP is used for server-side scripting.
  • HTML is used to create the structure of a web page, while CSS is used to style it.

With PHP, you can do a variety of tasks including:

  1. Dynamic web development: PHP can be used to dynamically generate HTML, CSS, and JavaScript, allowing for dynamic web pages and applications.

  2. Server-side scripting: PHP runs on the server, making it ideal for processing form data, handling sessions, and other server-side tasks.

  3. Database interaction: PHP can be used to interact with databases such as MySQL, Oracle, and PostgreSQL, allowing you to create dynamic and data-driven web pages.

  4. File handling: PHP provides functions to read, write, and manipulate files on the server, making it possible to create file upload and download features on your website.

  5. Email handling: PHP provides functions to send emails, making it easy to integrate email functionality into your web applications.

  6. Image manipulation: PHP provides libraries and functions to manipulate images, allowing you to create dynamic image galleries, resize images, and more.

  7. API development: PHP can be used to build RESTful APIs that can be consumed by other applications and services.

These are just a few examples of what can be done with PHP. With its wide range of functionality and ease of use, it remains a popular choice for web development.

6. ubuntu系统中php的安装和环境配置

(1)更新软件包列表,安装PHP及相关组件: 

apt update

apt install php-fpm php-mysqlnd php-gd php-mbstring

systemctl enable php7.4-fpm

(2)打开nginx的配置文件(通常位于/etc/nginx/nginx.conf),添加如下部分,

        location ~ \.php$ {
            root /home/01_html;
#            try_files $uri =404;
            fastcgi_pass unix:/run/php/php7.4-fpm.sock;
#            fastcgi_index index.php;
            fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
            include fastcgi_params;
            include snippets/fastcgi-php.conf;
        }

注意注释的两行,避免与 include snippets/fastcgi-php.conf; 中的部分冲突。

重启php7.4-fpm

systemctl restart php7.4-fpm

(3)注意以下路径php配置文件中的参数

/etc/php/7.4/fpm/pool.d/www.conf

user监听的用户和nginx配置文件中的是否一致,

listen路径是否为/run/php/php7.4-fpm.sock;

(4)验证Nginx配置文件是否有语法错误:

sudo nginx -t

参考资料:

运维排查篇 | 访问nginx出现403错误 - 知乎

阿里云CentOS8安装nginx+php-fpm_HjmaAs的博客-CSDN博客

PHP 简介 | 菜鸟教程

  • 3
    点赞
  • 26
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
您好!要安装配置Nginx,可以按照以下步骤进行操作: 1. 安装Nginx: 在Linux系统中,使用包管理器来安装Nginx。例如,在Ubuntu系统中,执行以下命令: ``` sudo apt update sudo apt install nginx ``` 2. 启动Nginx服务: 安装完成后,可以使用以下命令启动Nginx服务: ``` sudo systemctl start nginx ``` 3. 配置NginxNginx配置文件位于`/etc/nginx/nginx.conf`。您可以使用任何文本编辑器打开该文件进行编辑。 - 更改默认网站根目录: 默认情况下,Nginx的网站根目录位于`/var/www/html`。您可以根据需要更改此设置。在配置文件中找到以下行: ``` root /var/www/html; ``` 将其更改为您希望的目录,例如: ``` root /path/to/your/website; ``` - 设置虚拟主机: 如果您希望在同一服务器上托管多个网站,则可以配置虚拟主机。在配置文件中找到以下行: ``` server { listen 80; server_name your_domain.com; ... } ``` 将`your_domain.com`更改为您要使用的域名,并配置其他相关的设置。 - 配置SSL证书(可选): 如果您希望在Nginx上启用HTTPS,您需要获取并配置SSL证书。您可以通过使用免费的Let's Encrypt证书来实现。可以参考Let's Encrypt的官方文档来获得更详细的指导。 4. 重启Nginx: 在完成配置后,使用以下命令重启Nginx服务以使配置生效: ``` sudo systemctl restart nginx ``` 这些是基本的Nginx安装配置步骤。根据您的需求,还可以进行其他高级配置和优化。希望对您有所帮助!如有任何问题,请随时向我提问。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值