nginx的使用(一)-- 简单的安装使用

一、nginx简介

1、nginx是什么

Nginx (engine x) 是一个高性能的HTTP和反向代理服务,也是一个IMAP/POP3/SMTP服务。其特点是占有内存少,并发能力强,事实上nginx的并发能力确实在同类型的网页服务器中表现较好。

2、nginx可以用来做什么(不加载第三方模块)

  1. 反向代理
  2. 负载均衡
  3. HTTP服务器(包含动静分离)
  4. 正向代理
  5. 缓存

二、nginx安装以及简单的配置

1、安装nginx(环境 centos7)

采取最简单的方法,yum install nginx -y

2、配置nginx

① 修改user为root(你用来启动nginx的账户)
② 添加转发服务器

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
upstream web_server{ # 名字随便起
server 127.0.0.1:8080 max_fails=1 fail_timeout=10s; #Tomcat服务器1 ip
server 127.0.0.2:8080 max_fails=1 fail_timeout=10s; #Tomcat服务器2 ip
#注意服务器的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 / {
proxy_pass http://web_server; #和上边定义的upstream 对应起来
proxy_connect_timeout 10;
proxy_read_timeout 10;
proxy_send_timeout 10;
}
error_page 404 /404.html;
location = /40x.html {
}

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

3、nginx的启动、停止、重启

1
2
3
4
systemctl start nginx #启动nginx
systemctl stop nginx #停止nginx
systemctl restart nginx #重新启动nginx
systemctl enable nginx #开机启动nginx

4、nginx踩过的一些坑

selinux引起的权限访问受限问题,cat /var/log/Audit/Audit.log 发现有nginx访问阻止记录

1
type=AVC msg=audit(1416406823.013:3137): avc:  denied  { search } for  pid=15488 comm="nginx" name="www" dev="dm-3" ino=146 scontext=system_u:system_r:httpd_t:s0 tcontext=unconfined_u:object_r:user_home_dir_t:s0 tclass=dir

解决方案1、(建议采用
设置selinux允许nginx
1
2
3
yum install policycoreutils-python
cat /var/log/audit/audit.log | grep nginx | grep denied | audit2allow -M mynginx
semodule -i mynginx.pp

解决方案2.1、
临时关闭selinux
1
setenforce 0  #重启后失效

解决方案2.2、
永久关闭selinux

打开 selinux 配置文件

1
vim /etc/selinux/config

修改 selinux 配置文件
将SELINUX=enforcing改为SELINUX=disabled,保存后退出
1
2
3
4
5
6
7
8
9
10
11
# This file controls the state of SELinux on the system.
# SELINUX= can take one of these three values:
# enforcing - SELinux security policy is enforced.
# permissive - SELinux prints warnings instead of enforcing.
# disabled - No SELinux policy is loaded.
SELINUX=enforcing
# SELINUXTYPE= can take one of three two values:
# targeted - Targeted processes are protected,
# minimum - Modification of targeted policy. Only selected processes are protected.
# mls - Multi Level Security protection.
SELINUXTYPE=targeted

重启电脑(一定重启,否则无效)