nginx介绍

nginx是一个高性能的HTTP和反向代理服务器,也是一个电子邮件代理服务器,因它的稳定性、丰富的功能集、示例配置文件和低系统资源的消耗而闻名,其特点是占用内存少,并发能力强

nginx功能概述

HTTP基础功能

  • 处理静态文件,索引文件以及自动索引
  • 反向代理加速(无缓存),简单的负载均衡和容错
  • FastCGI,简单的负载均衡和容错
  • 模块化的结构

其他HTTP功能

  • 基于IP和名称的虚拟主机服务
  • Memcached的GET接口
  • 支持keep-alive和管道连接
  • 灵活简单的配置
  • 重新配置和在线升级而无须终端客户的工作进程
  • 可定制的访问日志,日志写入缓存,以及快捷的日志回卷
  • 4xx-5xx 错误代码重定向
  • 基于PCRE的rewrite重写模块
  • 基于客户端IP地址和HTTP基本认证的访问控制
  • PUT、DELETE和MKCOL方法
  • 支持FLV(flash视频)
  • 宽带限制

IMAP/POP3代理服务功能

  • 使用外部HTTP认证服务器重定向用户到IMAP/POP3后端
  • 使用外部HTTP认证服务器认证用户后连接重定向到内部的SMTP后端
  • SSL支持

nginx的优点

  1. 高性能的web服务器
  2. 可以作为负载均衡服务器
  3. 可以作为邮件代理服务器
  4. 安装简单,配置灵活

Nginx与Apache的相同与不同

相同点

Nginx与Apache都是web服务器,都是使用80端口

不同点:

  1. 异步非阻塞(nginx)、阻塞性(apache)
  2. 使用模型不同:nginx—epoll、kqueue,apache—select
  3. nginx:配置简单、可以http反向代理及加速缓存(负载均衡)、静态数据处理能力比apache高3倍以上(高并发)、消耗内存较少、有缓存功能、支持异步网络I/O时间epoll模型、对PHP需要其它后端调用才可使用(组件多) apache:配置复杂、对PHP支持简单、组件少

Nginx的安装

创建nginx用户

[root@localhost ~]# useradd -s /sbin/nologin -M nginx

安装需要的依赖包

[root@localhost ~]# yum -y install gcc gcc-c++ autoconf automake make pcre-devel zlib-devel openssl-devel

解压nginx安装包

首先需要下载nginx-1.6.0安装包

[root@localhost ~]# tar -zxvf nginx-1.6.0.tar.gz

编译安装nginx

[root@localhost nginx-1.6.0]# cd nginx-1.6.0/
[root@localhost nginx-1.6.0]# ./configure --prefix=/usr/local/nginx --with-http_ssl_module --sbin-path=/usr/sbin/nginx --user=nginx --group=nginx --with-http_gzip_static_module --add-module=/usr/src/ngx_brotli --http-log-path=/var/log/nginx/access.log --error-log-path=/var/log/nginx/error.log --pid-path=/var/run/nginx.pid 
[root@localhost nginx-1.6.0]# make && make install

添加软连接

[root@localhost nginx-1.6.0]# ln -s /usr/local/nginx/sbin/* /usr/local/sbin/

启动nginx

[root@localhost nginx-1.6.0]# nginx

添加nginx为系统服务

[root@localhost ~]# vim /usr/lib/systemd/system/nginx.service

[Unit]
Description=nginx - web server
After=network.target remote-fs.target nss-lookup.target

[Service]
Type=forking
PIDFile=/usr/local/nginx/logs/nginx.pid
ExecStartPre=/usr/local/nginx/sbin/nginx -t -c /usr/local/nginx/conf/nginx.conf
ExecStart=/usr/local/nginx/sbin/nginx -c /usr/local/nginx/conf/nginx.conf
ExecReload=/usr/local/nginx/sbin/nginx -s reload
ExecStop=/usr/local/nginx/sbin/nginx -s stop
ExecQuit=/usr/local/nginx/sbin/nginx -s quit
PrivateTmp=true

[Install]
WantedBy=multi-user.target

#重载服务配置
[root@localhost ~]# systemctl daemon-reload

# 启动nginx

[root@localhost ~]# systemctl start nginx.service

# 停止nginx

[root@localhost ~]# systemctl stop nginx.service

# 重启nginx

[root@localhost ~]# systemctl restart nginx.service

# 重载nginx配置

[root@localhost ~]# systemctl reload nginx.service

# 查看nginx状态

[root@localhost ~]# systemctl status nginx.service

# 将nginx加入开机自启

[root@localhost ~]# systemctl enable nginx.service
Created symlink from /etc/systemd/system/multi-user.target.wants/nginx.service to /usr/lib/systemd/system/nginx.service.

# 将nginx移除开机自启

[root@localhost ~]# systemctl disable nginx.service
Removed symlink /etc/systemd/system/multi-user.target.wants/nginx.service.

开启统计功能

修改nginx配置文件

[root@localhost nginx-1.6.0]# vim /usr/local/nginx/conf/nginx.conf
# 在server模块下填写以下代码
        location ~ /status {    # 访问位置:/status
            stub_status on;     # 开启统计功能
            access_log off;     # 关闭此模块的日志
        }

重载nginx配置文件

[root@localhost nginx-1.6.0]# killall -s HUP nginx

访问统计页面

[root@localhost nginx-1.6.0]# firefox 192.168.1.11/status

nginx平滑升级

首先下载nginx1.11.5安装包

解压nginx安装包

[root@localhost ~]# tar -zxvf nginx-1.11.5.tar.gz

编译nginx

[root@localhost ~]# cd nginx-1.11.5/
[root@localhost nginx-1.11.5]# ./configure --prefix=/usr/local/nginx/ --user=nginx --group=nginx --with-http_stub_status_module
[root@localhost nginx-1.11.5]# make
# 不要make install

备份nginx启动文件

[root@localhost nginx-1.11.5]# mv /usr/local/nginx/sbin/nginx /usr/local/nginx/sbin/nginx_$(date "+%Y-%m-%d_%H:%M:%S")

拷贝新的nginx启动文件

[root@localhost nginx-1.11.5]# cp objs/nginx /usr/local/nginx/sbin/

查询nginx版本号

[root@localhost nginx-1.11.5]# nginx -v
nginx version: nginx/1.11.5

nginx虚拟主机

修改hosts文件

[root@localhost ~]# echo "192.168.1.11 www.shuai.com" >> /etc/hosts

创建前端文件及存放目录

[root@localhost ~]# mkdir -p /www/html/shuai
[root@localhost ~]# echo "Welcome To www.shuaiguoer.com" > /www/html/shuai/index.html

修改nginx配置文件

[root@localhost ~]# vim /usr/local/nginx/conf/nginx.conf
# 在http模块下添加
    # 虚拟主机
    server {
        listen       80;                      # 监听端口
        server_name  www.shuai.com;             # 访问域名

location / {
root /www/html/shuai; # 网页路径
index index.html; # 网页类型
}


}

重载配置文件

[root@localhost ~]# killall -s HUP nginx

访问nginx

[root@localhost ~]# curl www.shuai.com
Welcome To www.shuaiguoer.com

开启nginx子配置项

# 创建虚拟主机配置文件存放目录
[root@localhost conf]# mkdir vhosts

# 修改nginx主配置文件
[root@localhost local]# cd /usr/local/nginx/conf/
[root@localhost conf]# vim nginx.conf
# 在http模块下添加
include /usr/local/nginx/conf/vhosts/*.conf;

# 检查nginx配置文件
[root@localhost conf]# nginx -t
nginx: the configuration file /usr/local/nginx/conf/nginx.conf syntax is ok
nginx: configuration file /usr/local/nginx/conf/nginx.conf test is successful

# 重载nginx配置文件
[root@localhost conf]# nginx -s reload

nginx反向代理

反向代理: 与一般访问流程相比,使用反向代理后,直接收到请求的服务器是代理服务器,然后将请求转发给内部网络上真正进行处理的服务器,得到的结果返回给客户端。反向代理隐藏了真实的服务器,为服务器收发请求,使真实服务器对客户端不可见。一般在处理跨域请求的时候比较常用。现在基本上所有的大型网站都设置了反向代理。

服务器IP地址:192.168.1.11

nginx反向代理其他服务

准备工作

首先安装一个 Tomcat 当做反向代理的服务
Tomcat首页地址:192.168.1.11:8080 # 安装好tomcat以后,在浏览器输入 http://192.168.1.11:8080/ 可以访问到Tomcat首页

修改hosts文件

[root@localhost vhosts]# vim /etc/hosts
# 最后一行添加
192.168.1.11 www.shuai.com www.tomcat.com

现在浏览器输入 http://www.tomcat.cn:8080/ 可以访问到Tomcat首页

配置nginx反向代理

# 切换到虚拟主机配置目录
[root@localhost conf]# cd vhosts/

# 新建一个虚拟主机
[root@localhost vhosts]# vim www.tomcat.cn.conf
server{
    listen      80;
    server_name www.tomcat.cn;

    location / {
        proxy_pass  http://www.tomcat.cn:8080;
    }
}

重载nginx配置文件

[root@localhost vhosts]# nginx -s reload

测试

现在访问 http://www.tomcat.cn/ 就可以访问Tomcat首页了

根据不同的访问路径进行反向代理

实现目标

  • 通过访问 http://www.tomcat.cn/one/ 跳转到 tomcat8080服务器
  • 通过访问 http://www.tomcat.cn/two/ 跳转到 tomcat8081服务器

准备工作

安装两个不同端口的Tomcat:8080、8081

在前文的基础上在新增一个tomcat服务器

[root@localhost ~]# cd /usr/local/
[root@localhost local]# cp -r tomcat8080/ tomcat8081/

# 修改Tomcat8081端口配置文件
[root@localhost local]# cd tomcat8081/conf/
[root@localhost conf]# vim server.xml
# 修改默认端口号:
<Server port="8015" shutdown="SHUTDOWN">
<Connector port="8081" protocol="HTTP/1.1"
<Connector port="8019" protocol="AJP/1.3" redirectPort="8443" />

# 启动Tomcat8081
[root@localhost conf]# cd ../bin/
[root@localhost bin]# ./startup.sh

查看两个Tomcat是否成功启动

[root@localhost bin]# netstat -ntpl | grep 808
tcp6       0      0 :::8080                 :::*                    LISTEN      5784/java       
tcp6       0      0 :::8081                 :::*                    LISTEN      5929/java

在两个Tomcat中创建测试页面

# Tomcat:8080:
[root@localhost two]# cd /usr/local/tomcat8080/webapps/
[root@localhost webapps]# mkdir one/
[root@localhost webapps]# cd one/
[root@localhost one]# vim index.html
Welcome to one:8080

# Tomcat:8081:
root@localhost bin]# cd /usr/local/tomcat8081/webapps/
[root@localhost webapps]# mkdir two/
[root@localhost webapps]# cd two/
[root@localhost two]# vim index.html
Welcome to two:8081

配置nginx反向代理

[root@localhost one]# cd /usr/local/nginx/conf/vhosts/
[root@localhost vhosts]# vim www.tomcat.cn.conf
server{
    listen      80;
    server_name www.tomcat.cn;

    location ~/one/ {
        proxy_pass  http://www.tomcat.cn:8080;
        root html;
        index index.php index.html;
    }
    location ~/two/ {
        proxy_pass  http://www.tomcat.cn:8081;
        root html;
        index index.php index.html;
    }

重载nginx配置文件

[root@localhost vhosts]# nginx -s reload

访问测试

[root@localhost vhosts]# curl http://www.tomcat.cn/one/
Welcome to one:8080

[root@localhost vhosts]# curl http://www.tomcat.cn/two/
Welcome to two:8081

反向代理中的其他参数

  • proxy_set_header:在将客户端请求发送给后端服务器之前,更改来自客户端的请求头信息;
  • proxy_connect_timeout:配置 Nginx 与后端代理服务器尝试建立连接的超时时间;
  • proxy_read_timeout:配置 Nginx 向后端服务器组发出 read 请求后,等待相应的超时时间;
  • proxy_send_timeout:配置 Nginx 向后端服务器组发出 write 请求后,等待相应的超时时间;
  • proxy_redirect:用于修改后端服务器返回的响应头中的 Location 和 Refresh。

跨域问题

什么是跨域???

  • 在浏览器上当前访问的网站向另一个网站发送请求获取数据的过程就是跨域请求。
  • 跨域是浏览器的同源策略决定的,是一个重要的浏览器安全策略,用于限制一个 origin 的文档或者它加载的脚本与另一个源的资源进行交互,它能够帮助阻隔恶意文档,减少可能被攻击的媒介,可以使用 CORS 配置解除这个限制。

举个栗子

# 同源的例子
http://example.com/app1/index.html  # 只是路径不同
http://example.com/app2/index.html

http://Example.com:80  # 只是大小写差异
http://example.com

# 不同源的例子
http://example.com/app1   # 协议不同
https://example.com/app2

http://example.com        # host不同
http://www.example.com
http://myapp.example.com

http://example.com        # 端口不同
http://example.com:8080

解决跨域

比如我的前端服务器是 http://pi.shuaiguoer.com/ 这个前端页面请求
http://pi.shuaiguoer.com:8080 下的资源,这个时候就出现了跨域

配置 header 解决跨域,只需要修改nginx配置文件就可以了

vim /usr/local/nginx/conf/nginx.conf

    server {
        listen       80;
        server_name  pi.shuaiguoer.com;

        add_header 'Access-Control-Allow-Origin' $http_origin;      # 全局变量获得当前请求origin,带cookie的请求不支持*
        add_header 'Access-Control-Allow-Credentials' 'true';       # 为 true 可带上 cookie
        add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';      # 允许请求方法
        add_header 'Access-Control-Allow-Headers' $http_access_control_request_headers;     # 允许请求的 header,可以为 *
        add_header 'Access-Control-Expose-Headers' 'Content-Length,Content-Range';      # 哪些首部可以作为响应的一部分暴露给外部。

重载nginx配置文件

sudo nginx -s reload

再次刷新页面浏览器就不会跨域问题了

nginx动静分离

使用前后端分离后,可以很大程度提升静态资源的访问速度,即使动态服务不可用,静态资源的访问也不会受到影响。

一般来说,都需要将动态资源和静态资源分开,由于 Nginx 的高并发和静态资源缓存等特性,经常将静态资源部署在 Nginx 上。如果请求的是静态资源,直接到静态资源目录获取资源,如果是动态资源的请求,则利用反向代理的原理,把请求转发给对应后台应用去处理,从而实现动静分离。
使用前后端分离后,可以很大程度提升静态资源的访问速度,即使动态服务不可用,静态资源的访问也不会受到影响。

创建动静态目录文件

  • www:存放静态资源
  • image:存放动态资源
[root@localhost html]# mkdir -p data/{www,image}

# 写入静态资源
[root@localhost html]# vim data/www/index.html

# 导入动态资源
[root@localhost html]# mv /AM.png data/image/

修改hosts文件

[root@localhost vhosts]# vim /etc/hosts
192.168.1.11 www.shuai.com www.tomcat.cn data.shuai.com

修改nginx配置文件

[root@localhost vhosts]# cd /usr/local/nginx/conf/vhosts/
[root@localhost vhosts]# vim data.shuai.com.conf
server{
    location /www {
        root    html/data/;
        index   index.html;
    }

    location /image {
        root    html/data/;
        autoindex on;
        autoindex_exact_size off;
        autoindex_localtime on;
    }
}

重载nginx配置文件

[root@localhost vhosts]# sudo nginx -s reload

访问测试

[root@localhost vhosts]# firefox http://data.shuai.com/www/

[root@localhost vhosts]# firefox http://data.shuai.com/www/

nginx负载均衡

可以再新建服务器(192.168.1.22)安装nginx

修改nginx配置文件

[root@localhost ~]# vim /usr/local/nginx/conf/nginx.conf
    # nginx轮询
    upstream shuaiguoer {
        server 192.168.1.11       weight=5;
        server 192.168.1.11:8080  weight=5;
        server 192.168.1.22       weight=5;
    }
    server {
        location / {
            proxy_pass  http://shuaiguoer;
        }
    }

重载配置文件

[root@localhost ~]# killall -s HUP nginx
[root@localhost ~]# curl 192.168.1.11
Welcome To www.shuaiguoer.com
[root@localhost ~]# curl 192.168.1.11
<!DOCTYPE html>
<html>
<head>
<title>Welcome to shuai!</title>
<style>

配置HTTPS

如何获取免费证书? 点击查看

[root@localhost ~]# vim /usr/local/nginx/conf/nginx.conf

server{
    listen  80;
    listen  443 ssl;
    server_name  *.shuaiguoer.com;
    ssl_certificate  /root/.acme.sh/pi.shuaiguoer.com/pi.shuaiguoer.com.cer;
    ssl_certificate_key  /root/.acme.sh/pi.shuaiguoer.com/pi.shuaiguoer.com.key;
    ssl_session_timeout  5m;
    ssl_protocols  TLSv1 TLSv1.1 TLSv1.2;
    ssl_ciphers  ECDHE-RSA-AES128-GCM-SHA256:HIGH:!aNULL:!MD5:!RC4:!DHE;
    ssl_prefer_server_ciphers  on;

    location / {
        root   html;
        index  index.php index.html index.htm;
    }
}

强制HTTPS

配置HTTP 301 永久重定向
第一种方法

[root@localhost ~]# vim /usr/local/nginx/conf/nginx.conf
# 直接在server模块中插入以下代码

if ($scheme = 'http') {
    return 301 https://$server_name$request_uri;
}

nginx完整配置文件

server{
    listen  80;
    listen  443 ssl;
    ssl_certificate  /root/.acme.sh/pi.shuaiguoer.com/pi.shuaiguoer.com.cer;
    ssl_certificate_key  /root/.acme.sh/pi.shuaiguoer.com/pi.shuaiguoer.com.key;
    server_name  pi.shuaiguoer.com;
    if ($scheme = 'http') {
        return 301 https://$server_name$request_uri;
    }
    ssl_session_timeout  5m;
    ssl_protocols  TLSv1 TLSv1.1 TLSv1.2;
    ssl_ciphers  ECDHE-RSA-AES128-GCM-SHA256:HIGH:!aNULL:!MD5:!RC4:!DHE;
    ssl_prefer_server_ciphers  on;

    location / {
        proxy_pass  http://pi.shuaiguoer.com:8080;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-Proto $scheme;
        proxy_set_header Host $http_host;
        proxy_set_header X-NginX-Proxy true;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "upgrade";
        proxy_max_temp_file_size 0;
        proxy_redirect off;
        proxy_read_timeout 240s;
    }
}

第二种方法

[root@localhost ~]# vim /usr/local/nginx/conf/nginx.conf
# 在最后加上以下代码(注意:是在上面server模块中,不占用80端口的情况下才能使用)

server{
    listen  80;
    server_name  pi.shuaiguoer.com;
    return 301 https://$server_name$request_uri;
}

nginx开启gzip压缩

修改nginx配置文件

[root@localhost ~]# vim /usr/local/nginx/conf/nginx.conf
# 压缩配置
gzip on                   # 开启起压缩功能
gzip_min_length 1k;       # 设置允许亚索页面的最小字节数,页面字节数从header头的Content-Length中获取。默认值是0,不管页面多大都进行压缩。建议设置成大于1k。如果小于1k,可能会越压越大。
gzip_buffers 4 16k;       # 表示申请4个单位为16k的内存作为压缩结果流缓存,默认值是申请与原始数据大小相同的内存空间来存储gzip压缩结果。
gzip_http_version 1.0;    # 压缩版本,默认1.1.用于设置识别HTTP协议版本。
gzip_comp_level 2;        # 压缩比率。用来指定GZIP压缩比,1压缩比最小,处理速度最快;9压缩比最大,传输速度最快,处理速度最慢,也比较消耗CPU资源。
gzip_types                # 用来指定压缩的类型,“text/html”文件总是会被压缩
gzip_vary on              # vary header支持,该选项是让CDN缓存服务器发给客户端的文件也要进行压缩。

重载配置文件

[root@localhost ~]# killall -s HUP nginx

nginx密码访问

修改nginx配置文件

[root@localhost ~]# vim /usr/local/nginx/conf/nginx.conf
# 在location中添加
            auth_basic  "Only master";                                # 认证名称(可随意填写)
            auth_basic_user_file  /usr/local/nginx/conf/.htpasswd;    # 认证的密码文件

重载配置文件

[root@localhost ~]# killall -s HUP nginx

安装httpd插件

[root@localhost ~]# yum -y install httpd-tools

创建master用户和密码

[root@localhost ~]# htpasswd -c /usr/local/nginx/conf/.htpasswd master
New password: 
Re-type new password: 
Adding password for user master

然后访问nginx测试

[root@localhost ~]# elinks 192.168.1.11:8080
# 或是使用本地浏览器访问

Last modification:June 2nd, 2023 at 10:23 am
如果觉得我的文章对你有用,请随意赞赏