当前位置:首页 > web安全培训 > 正文

手动部署LNMP环境系列之第三章:Nginx安装与配置教程

手动部署LNMP环境系列之第三章:Nginx安装与配置教程

手动部署LNMP环境系列之第三章:Nginx安装与配置教程 LNMP(Linux + Nginx + MySQL + PHP)是一个常用的Web开发环境。本系列文章将...

手动部署LNMP环境系列之第三章:Nginx安装与配置教程

LNMP(Linux + Nginx + MySQL + PHP)是一个常用的Web开发环境。本系列文章将以CentOS 7为例,讲述如何手动部署LNMP环境。第三章将重点讲解Nginx的安装与配置。

1. 安装Nginx


(1)首先,安装Nginx需要先安装EPEL源。命令如下:


```
yum install epel-release -y
```

(2)安装Nginx,命令如下:


```
yum install nginx -y
```

(3)启动Nginx服务并设置开机自启,命令如下:


```
systemctl start nginx
systemctl enable nginx
```

安装完成后,Nginx的配置文件位于/etc/nginx/nginx.conf中。


2. 配置Nginx


(1)备份默认的Nginx配置文件:

手动部署LNMP环境系列之第三章:Nginx安装与配置教程


```
mv /etc/nginx/nginx.conf /etc/nginx/nginx.conf.default
```

(2)创建新的Nginx配置文件,命令如下:


```
vi /etc/nginx/nginx.conf
```

在新的配置文件中,可以按需配置各项参数,例如:


```
user nginx;
worker_processes auto;
error_log /var/log/nginx/error.log warn;
pid /var/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;
tcp_nopush on;
tcp_nodelay on;
keepalive_timeout 65;
gzip on;
include /etc/nginx/conf.d/*.conf;
}
```

其中,配置文件的格式会影响Nginx的性能。建议不要直接复制粘贴以上配置文件,而应根据实际需求逐一配置。


(3)检查Nginx配置文件并重启服务:


```
nginx -t && systemctl restart nginx
```

3. 添加虚拟主机


(1)在/etc/nginx/conf.d目录下,创建虚拟主机的配置文件,例如:


```
vi /etc/nginx/conf.d/www.example.com.conf
```

在文件中添加以下内容:


```
server {
listen 80;
server_name www.example.com;
root /var/www/example.com;
location / {
index index.html index.htm index.php;
}
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;
}
}
```

其中,www.example.com为虚拟主机的域名,/var/www/example.com为虚拟主机的根目录。


(2)检查Nginx配置文件并重启服务,命令如下:


```
nginx -t && systemctl restart nginx
```

在浏览器中输入www.example.com即可访问该虚拟主机。


本文简单介绍了如何在CentOS 7上手动安装及配置Nginx。下一篇文章将深入讲解如何安装及配置MySQL。


最新文章