本文主要介绍 Nginx 的安装和常用配置。
1. 概述
nginx(engine x) 是一个HTTP服务器/反向代理服务器、邮件代理服务器、 TCP/UDP 代理服务器,最初由 Igor Sysoev 开发的,在很长的一段时间里, nginx 运行在很多高负载的俄罗斯网站上,包括 Yandex, Mail.Ru, VK, and Rambler 。
nginx 具有占用内存少,并发能力强的特点,事实上 nginx 的并发能力确实在同类型的网页服务器中表现较好。
2. 安装
本文使用 yum 命令安装 nginx ,如下:
yum install -y nginx.x86_64
使用的 yum 源为 epel , epel 源相关配置点击此处。
3. 常用配置
3.1 默认配置
安装完 nigix 之后,首先使用默认配置启动 nginx ,测试 nginx 是否能够正常工作,如下:
[root@node1 ~]# nginx [root@node1 ~]# [root@node1 ~]# ps -ef|grep nginx root 2711 1 0 20:27 ? 00:00:00 nginx: master process nginx nginx 2712 2711 0 20:27 ? 00:00:00 nginx: worker process root 2714 2621 0 20:27 pts/1 00:00:00 grep --color=auto nginx [root@node1 ~]#
在web浏览器中打开 nginx 服务器地址,如下:
从上面web浏览器的显示结果能够看到, nginx 服务器已经正常启动了。
3.2 常用配置
通常我们都需要根据实际情况,修改 nginx 的配置。
nginx 的配置文件存放在 /etc/nginx 下,如下:
上述文件中的 nginx.conf 是 nginx 的主配置文件,通常我们只需要修改该配置文件即可,其余配置文件,一般只需要使用默认提供的即可。
安装 nginx 之后的 nginx.conf 默认配置如下(去掉一些注释):
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 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 { } } }
nginx.conf 中的配置项说明如下:
- worker_processes:表示工作进程的数量,一般设置为 cpu 的核数
- worker_connections:表示每个工作进程的最大连接数
- server{}:定义虚拟主机,在 server{} 块中,又存在以下配置:
1)listen:监听的端口,如 80
2)server_name:监听的域名,如 localhost
3)location{}:对匹配的 URI 进行配置。例如 location / { } ,该 location 可匹配任何查询,因为所有 http 请求都以“/”开头的
4)root:指定对应 URL 的资源查找路径。在本例中,资源查找路径为 /usr/share/nginx/html
根据上述配置的解释,默认的 nginx 配置监听了 80 端口、在 /usr/share/nginx/html 路径中查找资源。在服务器的 /usr/share/nginx/html 路径下,存在以下文件:
所以当我们在浏览器输入nginx 服务器地址、访问 nginx 服务器时,就能够在浏览器中看到 nginx 测试页面,实际上我们访问的是 /usr/share/nginx/html/index.html 这个文件。