# Nginx 服务器搭建

> 来源：梦飞idc云平台 | 原文：https://www.mfisp.com/19823.html | 发布：2023-04-20 | 更新：2023-04-20 | 分类：服务器vps推荐、运维技术

一、什么是 Nginx ？

 

Nginx 与 Apache IIS 等软件一样，是一款**服务器软件**，为 web 站点提供服务

 

除此之外，Nginx 还是一款**反向代理服务器**，我们可以利用 Nginx 实现负载均衡

 

所谓负载均衡是指为了减少服务器压力，需要将用户访问信息引入内部不同的服务器，分担服务器压力

 

二、Nginx 与其他服务器对比

 

IIS：IIS 服务器只能运行在 Windows 上，效率远不如 Linux 服务器

 

Tomcat ：面向 java 语言，是一款重量级服务器

 

Apache ： 目前应用最多的服务器软件，稳定，开源，跨平台，缺点是不支持高并发、rewrite 模块强大

 

Nginx ： 轻量级、支持高并发（支持 10 万以上 TCP 连接）、部署简单、内存消耗小、成本低、rewrite 模块不够强大

 

三、Nginx 服务器搭建

 

1.安装环境 Ubuntu16.04

 

通过 apt-get 安装

 

```
sudo apt-get install nginx
```

 

2.然后安装 *PHP*FastCGI 管理器 php7.0-fpm

 

```
sudo apt-get install php-fpm
```

 

3.安装完成后配置 nginx

 

```
vim /etc/ngnix/sites-avaiable/default
```

 

4.配置监听端口：

 

```
listen 8080 default_server;       #IPV4端口
listen [::]:8080 default_server;  #IPV6端口
```

 

5.配置 WEB 根站点目录

 

```
root /var/www/nginx/;
```

 

6.配置 nginx 与 php：

 

nginx 与 fastcgi 通信有 2 种方式：socket 和 TCP

 

```
location ~ \.php$ {
      include snippets/fastcgi-php.conf;   #取消注释这一行
      #       # With php7.0-cgi alone:
      #       fastcgi_pass 127.0.0.1:9000;
      #       # With php7.0-fpm:
      fastcgi_pass unix:/run/php/php7.0-fpm.sock;    #设置socket方式
}
```

 

7.重启 ngnix

 

```
service nginx restart
```

 

8.测试配置文件是否生效

 

```
/usr/sbin/nginx -t
```

 

9.改 php-fpm 配置文件

 

```
sudo vim /etc/php/7.0/fpm/pool.d/www.conf
```

 

```
; 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 IPv4 address on
;                            a specific port;
;   '[ip:6:addr:ess]:port' - to listen on a TCP socket to a specific IPv6 address on
;                            a specific port;
;   'port'                 - to listen on a TCP socket to all addresses
;                            (IPv6 and IPv4-mapped) on a specific port;
;   '/path/to/unix/socket' - to listen on a unix socket.
; Note: This value is mandatory.
listen = /run/php/php7.0-fpm.sock   #与nginx配置文件中保持一致
```

 

10.重启 php-fpm

 

```
service php7.0-fpm restart
```

 

11.测试配置文件是否生效

 

```
php-fpm7.0 -t
```

 

12.至此就完成了 nginx 和 PHP 的搭建

 

注意：当 apache 和 nginx 安装在同一台主机上时需要修改各自的监听端口，避免冲突

 

apache：

 

```
vim /etc/apache2/ports.conf
```

 

ginx：

 

```
vim /etc/nginx/sites-avaiable/default
```

---
本页由 梦飞idc云平台（https://www.mfisp.com）提供。站点导航见 https://www.mfisp.com/llms.txt
