当前位置:首页 > 技术文章 > 正文内容

Nginx教程

arlanguage5个月前 (12-12)技术文章39

Nginx

Nginx
1. 基本概念
2. centos7部署nginx
1. 部署前准备
2. 安装nginx
3. 配置文件
1. nginx目录结构
2. 默认的nginx.conf
1. nginx.conf内容结构:
2. nginx.conf内容格式说明:
3. location 语法详解
1. 语法规则:
2. 释义:
3. 举例子:
4. location中 rewrite 语法:
5. root 和 alias 用法
1. root的用法
2. alias 的用法
4. 常用配置
1. http(静态)服务器
2. 反向代理
3. Redirect(重定向)语法
4. 防盗链
5. 配置https
1. 前提准备
2. 配置https
1. 查看是否开启ssl模块
2. 如果不存在ssl模块,下面进行安装
3. 配置ssl证书
4. 配置 nginx.conf https
5. HTTP 自动跳转 HTTPS 的安全配置
6. 负载均衡
1. 轮询
2. 权重
3. iphash
4. 最少连接
5. fair

1. 基本概念

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

Nginx专为性能优化而开发,性能是其最重要的考量,实现上非常注重效率,能经受高负载的考验,据报告能支持高达50,000个并发连接数

2. centos7部署nginx

1. 部署前准备

  1. 安装gcc
  • # 查看是否安装gcc和版本
    gcc -v
    # 一般阿里云的centOS7里面是都有的,没有安装的话会提示命令找不到
    # 如果未安装gcc,请安装
    yum -y install gcc
  1. 安装 pcre、pcre-devel
  • pcre是一个perl库,包括perl兼容的正则表达式库,nginx的http模块使用pcre来解析正则表达式,所以需要安装pcre库。
  • # 安装命令
    yum install -y pcre pcre-devel
  1. 安装 zlib
  • zlib库提供了很多种压缩和解压缩方式nginx使用zlib对http包的内容进行gzip,所以需要安装
  • # 安装命令
    yum install -y zlib zlib-devel
  1. 安装 openssl
  • openssl是web安全通信的基石,没有openssl,可以说我们的信息都是在裸奔。。。
  • yum install -y openssl openssl-devel

2. 安装nginx

  1. 部署nginx
  • # 1. 新建nginx目录
    mkdir /usr/local/nginx
    cd /usr/local/nginx
    # 2. 下载nginx安装包
    wget http://nginx.org/download/nginx-1.18.0.tar.gz
    # 3. 解压缩包
    tar -zxvf nginx-1.18.0.tar.gz
    # 4. 切换到解压的目录
    cd /usr/local/nginx/nginx-1.18.0
    # 5. 执行configure脚本,
    ./configure
    #若想要开启某些功能或模块的可以添加参数,例如下面这里开启 http sll模块
    ./configure --prefix=/usr/local/nginx --with-http_stub_status_module --with-http_ssl_module
    # 6. 编译
    make
    # 7. 安装
    make install
    # 切换目录
    cd /usr/local/nginx/sbin
    # 启动nignx
    ./nginx # 也可以指定配置文件启动,例如 ./nginx -c ../conf/nginx.conf
  • 使用ip:80访问到如下页面说明nginx部署成功
  • Figure :

3. 配置文件

1. nginx目录结构

[root@localhost ~]# tree /usr/local/nginx
/usr/local/nginx
├── client_body_temp
├── conf # Nginx所有配置文件的目录
│ ├── fastcgi.conf # fastcgi相关参数的配置文件
│ ├── fastcgi.conf.default # fastcgi.conf的原始备份文件
│ ├── fastcgi_params # fastcgi的参数文件
│ ├── fastcgi_params.default
│ ├── koi-utf
│ ├── koi-win
│ ├── mime.types # 媒体类型
│ ├── mime.types.default
│ ├── nginx.conf # Nginx主配置文件
│ ├── nginx.conf.default
│ ├── scgi_params # scgi相关参数文件
│ ├── scgi_params.default
│ ├── uwsgi_params # uwsgi相关参数文件
│ ├── uwsgi_params.default
│ └── win-utf
├── fastcgi_temp # fastcgi临时数据目录
├── html # Nginx默认站点目录
│ ├── 50x.html # 错误页面优雅替代显示文件,例如当出现502错误时会调用此
│ └── index.html # 默认的首页文件
├── logs # Nginx日志目录
│ ├── access.log # 访问日志文件
│ ├── error.log # 错误日志文件
│ └── nginx.pid # pid文件,Nginx进程启动后,会把所有进程的ID号写到此
├── proxy_temp # 临时目录
├── sbin # Nginx命令目录
│ └── nginx # Nginx的启动命令
├── scgi_temp # 临时目录
└── uwsgi_temp # 临时目录nginx.conf

2. 默认的nginx.conf

#user nobody;
worker_processes 1; # 工作进程:数目。根据硬件调整,通常等cup数量或者2倍cpu数量。
# 错误日志存放路径
#error_log logs/error.log;
#error_log logs/error.log notice;
#error_log logs/error.log info;
#pid logs/nginx.pid; # nginx进程pid存放路径
events {
worker_connections 1024; # 工作进程的最大连接数量
}
http {
include mime.types; # 指定mime类型,由mime.type来定义
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 logs/access.log main; # 用log_format指令设置日志格式后,需要用access_log来指定日志文件存放路径
sendfile on; # 指定nginx是否调用sendfile函数来输出文件,对于普通应用,必须设置为on;如果用来进行下载等应用磁盘io重负载应用,可设置off,以平衡磁盘与网络io处理速度,降低系统uptime
#tcp_nopush on; # 此选项允许或禁止使用socket的TCP_CORK的选项,此选项仅在sendfile的时候使用

# keepalive超时时间
#keepalive_timeout 0;
keepalive_timeout 65;
#gzip on; # 开启gzip压缩服务

# 虚拟主机
server {
listen 80; # 配置监听端口号
server_name localhost; # 配置访问域名,域名可以有多个,用空格隔开
#charset koi8-r; # 字符集设置
#access_log logs/host.access.log main;
location / {
root html;
index index.html index.htm;
}
# 错误跳转页
#error_page 404 /404.html;
# redirect server error pages to the static page /50x.html
#
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root html;
}
# proxy the PHP scripts to Apache listening on 127.0.0.1:80
#
#location ~ \.php$ {
# proxy_pass http://127.0.0.1;
#}
# pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
#
#location ~ \.php$ { # 请求的url过滤,正则匹配,~为区分大小写,~*为不区分大小写。
# root html; # 根目录
# fastcgi_pass 127.0.0.1:9000; # 请求转向定义的服务器列表
# fastcgi_index index.php; # 如果请求的 Fastcgi_index URI是以 / 结束的,该指令设置的文件会被附加到URI的后面并保存在变量$fastcig_script_name中
# fastcgi_param SCRIPT_FILENAME /scripts$fastcgi_script_name;
# include fastcgi_params;
#}
# deny access to .htaccess files, if Apache's document root
# concurs with nginx's one
#
#location ~ /\.ht {
# deny all;
#}
}
# another virtual host using mix of IP-, name-, and port-based configuration
#
#server {
# listen 8000;
# listen somename:8080;
# server_name somename alias another.alias;
# location / {
# root html;
# index index.html index.htm;
# }
#}
# HTTPS server
#
#server {
# listen 443 ssl; # 监听端口
# server_name localhost; # 域名
# ssl_certificate cert.pem; # 证书位置
# ssl_certificate_key cert.key; # 私钥位置
# ssl_session_cache shared:SSL:1m;
# ssl_session_timeout 5m;
# ssl_ciphers HIGH:!aNULL:!MD5; # 密码加密方式
# ssl_prefer_server_ciphers on;
# location / {
# root html;
# index index.html index.htm;
# }
#}
}

1. nginx.conf内容结构:

... #全局块
events { #events块
...
}
http #http块
{
... #http全局块
server #server块
{
... #server全局块
location [PATTERN] #location块
{
...
}
location [PATTERN]
{
...
}
}
server
{
...
}
... #http全局块
}

2. nginx.conf内容格式说明:

  • 全局块:配置nginx全局的指令,一般为nginx服务器的用户组、nginx进程pid路径、日志路径、配置文件引入
  • events块:配置 Nginx 服务器与用户的网络连接,包括开启对多个work process的网络连接进行序列化、是否允许同时接收多个网络连接、选取事件驱动模型、work process支持的最大连接数等
  • http块
    • http全局块: 文件引入、日志自定义、连接超时时间、单链接请求数上限等。
    • server块:虚拟注解的配置
      • 全局server块:虚拟主机的名称或IP配置等
      • location块:配置请求的路由,以及各种页面的处理情况

3. location 语法详解

1. 语法规则:

// []中的 | 表示或者,实际只能填写一个一种开头语法
location [=|~|~*|^~] /uri/ {
...
...
}

2. 释义:

  • = 开头表示精确匹配
  • ^~ 开头表示uri以某个常规字符串开头,理解为匹配 url 路径即可。nginx不对 url 做编码,因此请求为 /static/20%/aa,可以被规则 ^~/static/ /aa(aa前面的 / 前是空格)。 以xx开头
  • ~ 开头表示区分大小写的正则匹配 以xx结尾
  • ~* 开头表示不区分大小写的正则匹配 以xx结尾
  • !~ 和 !~* 分别表示区分大小写 不匹配 和不区分大小写 不匹配 的正则
  • / 表示通用匹配,任何请求都会匹配到

》》》正则表达可以点击查看正则表达式

注意:如果一个uri有多个location块匹配时,nginx会选择前缀最长的块。第一个location 块是 / ,前缀最短,长度为1,所以只用当其他所有 location 块都未匹配到时,才会使用此块。

3. 举例子:

location = / {
#规则A
}
location = /login {
#规则B
}
location ^~ /static/ {
#规则C
}
location ~ \.(gif|jpg|png|js|css)$ {
#规则D,注意:是根据括号内的大小写进行匹配。括号内全是小写,只匹配小写
}
location ~* \.png$ {
#规则E
}
location !~ \.xhtml$ {
#规则F
}
location !~* \.xhtml$ {
#规则G
}
# 效果
访问根目录/, 比如http://localhost/ 将匹配规则A
访问 http://localhost/login 将匹配规则B,http://localhost/register 则匹配规则H
访问 http://localhost/static/a.html 将匹配规则C
访问 http://localhost/a.gif, http://localhost/b.jpg 将匹配规则D和规则E,但是规则D顺序优先,规则E不起作用, 而 http://localhost/static/c.png 则优先匹配到 规则C
访问 http://localhost/a.PNG 则匹配规则E, 而不会匹配规则D,因为规则E不区分大小写。
访问 http://localhost/a.xhtml 不会匹配规则F和规则G,

4. location中 rewrite 语法:

  • last – 基本上都用这个Flag。
  • break – 中止Rewirte,不再继续匹配
  • redirect – 返回临时重定向的HTTP状态302
  • permanent – 返回永久重定向的HTTP状态301

5. root 和 alias 用法

nginx指定文件路径有两种方式root和alias,root与alias主要区别在于nginx如何解析location后面的uri,这会使两者分别以不同的方式将请求映射到服务器文件上,说白了就是两者拼接文件路径的方式不一样。

1. root的用法

句法: root path;
默认: root html;
语境: http,server,location,if in location

示例:

location /a/ {
root /usr/local/nginx_http_test/;
}

当客户端请求/a/cat.jpg的时候,Nginx把请求解析映射为 /usr/local/nginx_http_test/a/cat.png

2. alias 的用法

句法: alias path;
默认: -
语境: location # 只用于location中

示例:

location /a/ {
alias /usr/local/nginx_http_test/;
}

当客户端请求 /a/cat.jpg 的时候,Nginx把请求映射为 /usr/local/nginx_http_test/cat.jpg
因为alias会把location后面配置的路径丢弃掉(比如/request_path/dir/a.html,到alias那里就剩a.html了),把当前匹配到的目录指向到指定的目录。

注意:

  1. 使用alias时,目录名后面一定要加"/",否则会认为是个文件。
  2. alias在使用正则匹配时,location后uri中捕捉到要匹配的内容后,并在指定的alias规则内容处使用。
  3. alias只能位于location块中,而root不限于location。

4. 常用配置

1. http(静态)服务器

这样如果访问http://localhost 就会默认访问到/usr/local/myhtml目录下面的index.html,如果一个网站只是静态页面的话,那么就可以通过这种方式来实现部署。


server {
listen 80;
server_name localhost;
client_max_body_size 1024M;


location / {
root /usr/local/myhtml; //思路:通过/将所有的请求,转发给root处理
index index.html;
}
}

2. 反向代理

这样访问localhost的时候,就相当于访问localhost:8080了

server {
listen 80;
server_name localhost;
client_max_body_size 1024M;
location / {
proxy_pass http://localhost:8080;
proxy_set_header Host $host:$server_port; //思路:通过/,将所有的请求,转发给第3方处理
}
}

3. Redirect(重定向)语法


server {
listen 80;
server_name start.igrow.cn;
index index.html index.php;
root html;
if ($http_host !~ "^star\.igrow\.cn#34; {
rewrite ^(.*) http://star.igrow.cn$1 redirect;
}
}

4. 配置https

1. 前提准备

  1. 服务器已经安装nginx并且通过http可以正常访问
  2. 拥有ssl证书,没有的可以去阿里购买或者免费申请一年

2. 配置https

1. 查看是否开启ssl模块

在配置ssl证书之前,要确保你的nginx已经安装了ssl模块,一般情况下自己安装的nginx都是不存在ssl模块的。

这里先检查下自己是否存在ssl模块:

cd /usr/local/nginx/sbin
# 这里是大写V,小写v只展示版本号
./nginx -V

控制台输出结果:

[root@VM-0-10-centos sbin]# ./nginx -V
nginx version: nginx/1.18.0
built by gcc 4.8.5 20150623 (Red Hat 4.8.5-44) (GCC)
built with OpenSSL 1.0.2k-fips 26 Jan 2017
TLS SNI support enabled
configure arguments:

如果出现 (configure arguments: --with-http_ssl_module), 则已安装(下面的步骤可以跳过,直接进行第3步

2. 如果不存在ssl模块,下面进行安装

  1. 进入到你的解压缩包后的nginx目录,注意这里不是nginx安装目录,是解压缩后的目录,我的是在/usr/local/nginx/nginx-1.18.0
  • # 切换目录
    cd /usr/local/nginx/nginx-1.18.0
    # 添加ssl模块
    ./configure --prefix=/usr/local/nginx --with-http_stub_status_module --with-http_ssl_module
    # 编译
    make
    #切记不要执行make install,否则会重新安装nginx
  • 上述命令执行完成后,/usr/local/nginx/nginx-1.18.0 目录中会出现 objs 文件夹,内部存在nginx文件:
  1. 用 /usr/local/nginx/nginx-1.18.0/objs/nginx 文件 替换掉之前安装包 /usr/local/nginx/sbin/nginx 文件
  • #停止nginx服务
    ./nginx -s stop
    #用新生成的nginx文件替换之前的nginx文件
    cp /usr/local/nginx/nginx-1.18.0/objs/nginx /usr/local/nginx/sbin/
    # 查看安装情况
    cd /usr/local/nginx/sbin
    ./nginx -V
  • 控制台输出结果:
  • [root@VM-0-10-centos sbin]# ./nginx -V
    nginx version: nginx/1.18.0
    built by gcc 4.8.5 20150623 (Red Hat 4.8.5-44) (GCC)
    built with OpenSSL 1.0.2k-fips 26 Jan 2017
    TLS SNI support enabled
    configure arguments: --prefix=/usr/local/nginx --with-http_stub_status_module --with-http_ssl_module

3. 配置ssl证书

解压缩下载好的证书(证书一般是pem文件和key文件,这里名字可以随便改)

将下载好的证书上上传到服务器,我将证书放在了/root/domain_cert目录下

4. 配置 nginx.conf https

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

配置:

Nginx 版本为 nginx/1.15.0 以上请使用 listen 443 ssl 代替 listen 443 和 ssl on

# HTTPS server
#
server {
# SSL 监听端口
listen 443 ssl;
# 填写绑定证书的域名
server_name www.test.xyz;
# ssl证书pem文件或者crt文件路径
ssl_certificate /root/domain_cert/www.text.xyz.pem;
# ssl证书key文件路径
ssl_certificate_key /root/domain_cert/www.text.xyz.key;
# ssl_session_cache shared:SSL:1m;
ssl_session_timeout 5m;
# 按照如下协议配置
ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
# 按照如下协议配置,配置加密套件,写法遵循 openssl 标志
ssl_ciphers ECDHE-RSA-AES128-GCM-SHA256:HIGH:!aNULL:!MD5:!RC4:!DHE;
ssl_prefer_server_ciphers on;
location / {
# 要代理的项目路径
proxy_pass http://localhost:8080;
#root html;
#index index.html index.htm;
}
}

校验nginx.conf文件是否正确

./nginx -t

若校验配置文件正常,重启nginx,即可使用 https:www.test.xyz访问。

5. HTTP 自动跳转 HTTPS 的安全配置

  1. 根据实际需求,选择以下配置方式:
  • 在页面中添加 JS 脚本。
  • 在后端程序中添加重定向。
  • 通过 Web 服务器实现跳转。
  • Nginx 支持 rewrite 功能。若您在编译时没有去掉 pcre,您可在 HTTP 的 server 中增加 return 301 https://$host$request_uri;,即可将默认80端口的请求重定向为 HTTPS。修改如下内容:

server {
listen 80;
#填写绑定证书的域名
server_name cloud.tencent.com;
#把http的域名请求转成https
# return 301 https://$host$request_uri;
rewrite ^(.*)$ https://$host$1 permanent;
}

# 关闭
./nginx -s stop
# 启动
./nginx
# 重载,要开启之后才能执行这条命令
./nginx -s reload

6. 负载均衡

1. 轮询

轮询方式是Nginx负载默认的方式,顾名思义,所有请求都按照时间顺序分配到不同的服务上,如果服务Down掉,可以自动剔除,如下配置轮询 8081、8082、8083 tomcat服务

http {
include mime.types;
default_type application/octet-stream;

...
...

#gzip on;
# 负载均衡的服务
upstream tomcat {
server localhost:8081;
server localhost:8082;
server localhost:8083;
}

# 我这里是新增了一个server节点,也可以修改已经有的server节点,看自己需求了
server {
# 这里用了另外一个接口做负载均衡
listen 8084;
server_name localhost;
location / {
# 代理访问负载均衡服务
proxy_pass http://tomcat;
}
}
}

2. 权重

指定每个服务的权重比例,weight和访问比率成正比,权重越高被访问的机率就越大;通常用于后端服务机器性能不统一,将性能好的分配权重高来发挥服务器最大性能,如下给 8081、8082、8083 tomcat服务配置了不同的权重。

upstream tomcat {
server localhost:8081 weight=10;
server localhost:8082 weight=20;
server localhost:8083 weight=30;
}

3. iphash

每个请求都根据访问ip的hash结果分配,经过这样的处理,每个访客固定访问一个后端服务,(ip_hash可以和weight配合使用)。

upstream tomcat {
ip_hash;
server localhost:8081;
server localhost:8082;
server localhost:8083;
}

4. 最少连接

将请求分配到连接数最少的服务上。

upstream tomcat {
least_conn;
server localhost:8081;
server localhost:8082;
server localhost:8083;
}

5. fair

按后端服务器的响应时间来分配请求,响应时间短的优先分配。

upstream tomcat {
fair;
server localhost:8081;
server localhost:8082;
server localhost:8083;
}

扫描二维码推送至手机访问。

版权声明:本文由AR编程网发布,如需转载请注明出处。

本文链接:http://www.arlanguage.com/post/101.html

标签: nginx if语法
分享给朋友:

“Nginx教程” 的相关文章

Docker搭建开发环境(Nginx+MySQL+PHP)

注意事项1、像MySQL配置文件、Nginx配置文件、网站根目录这种比较经常操作的需要先使用 docker cp 将文件从容器里复制到主机目录,docker run的时候直接挂载目录就可以了2、docker run MySQL和Nginx的时候注意使用 --link实现容器之间通信3、运行容器的时候...

如何让Nginx更安全? nginx怎么保证高可用

网络安全的重要性不言而喻。那么小伙伴们有没有在日常使用 Nginx 的时候,特意去关注下它的安全配置呢?今天松哥和小伙伴们讨论一下如何安全的使用 Nginx,给大伙几个建议。一 使用最新版建议使用最新版的 Nginx,对于已经部署的 Nginx,要及时更新到最新版本,以确保所有已知的安全漏洞都已修补...

Nginx 最全操作——nginx配置(2)

nginx 配置基本结构main # 全局配置,对全局生效 ├── events # 配置影响 nginx 服务器或与用户的网络连接 ├── http # 配置代理,缓存,日志定义等绝大多数功能和第三方模块的配置 │ ├── upstream # 配置后端服务器具体地址,负...

「网络」运维需要掌握的 17 个实用技巧

1、查找当前目录下所有以.tar结尾的文件然后移动到指定目录find . -name “*.tar” -execmv {}./backup/ ;注解:find –name 主要用于查找某个文件名字,-exec 、xargs可以用来承接前面的结果,然后将要执行的动作,一般跟find在一起用的很多,fi...

SeaTunnel 实践 | SeaTunnel 帮你快速玩转 Spark 数据处理

Databricks 开源的 Apache Spark 对于分布式数据处理来说是一个伟大的进步。我们在使用 Spark 时发现了很多可圈可点之处,我们在此与大家分享一下我们在简化 Spark 使用和编程以及加快 Spark 在生产环境落地上做的一些努力。01一个 Spark Streaming 读取...

宝塔面板通过可视化界面来管理云服务器的运维软件

宝塔面板是专门给广大普通用户通过可视化界面来管理你的云服务器(Linux或者Window系统),节省操作服务器的时间和精力成本,可以一键安装和搭建网站,可以一键安装PHP运行环境,一键安装java运行环境,一键安装各种开发环境.普通人用的最多的就是搭建和部署网站.例如:宝塔面板是一款服务器管理软件,...