nginx 安装和使用

邱秋 • 2018年01月25日 • 阅读:1670 • nginx

Nginx 安装使用

For RHEL/CentOS

$ sudo yum install yum-utils -y

#手动写入rpm源
# 在  /etc/yum.repos.d/nginx.repo 写入如下内容

[nginx-stable]
name=nginx stable repo
baseurl=http://nginx.org/packages/centos/$releasever/$basearch/
gpgcheck=1
enabled=1
gpgkey=https://nginx.org/keys/nginx_signing.key

[nginx-mainline]
name=nginx mainline repo
baseurl=http://nginx.org/packages/mainline/centos/$releasever/$basearch/
gpgcheck=1
enabled=0
gpgkey=https://nginx.org/keys/nginx_signing.key

$ sudo yum-config-manager --enable nginx-mainline
$ sudo yum install nginx -y

其他平台 直接 访问 http://nginx.org/en/linux_packages.html#stable

nginx.pid 失败问题 执行 sudo nginx -c /usr/local/etc/nginx/nginx.conf sudo nginx -s reload #重启 sudo nginx -t #测试配置文件

nginx 反向代理

server {
    listen       80 default_server;
    listen       [::]:80 default_server;
    server_name  chuchur.com www.chuchur.com;
    #/rest/ 开头的转到7002
    location /rest/ {
        proxy_pass http://127.0.0.1:7002/;
        proxy_redirect  off;
        proxy_set_header        HOST  $host;
        proxy_set_header        X-Real-IP       $remote_addr;
        proxy_set_header        X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_send_timeout      300;
        proxy_read_timeout      300;
    }

    #其他的转发到7001
    location / {
        proxy_pass http://127.0.0.1:7001;
        proxy_redirect  off;
        proxy_set_header        HOST  $host;
        proxy_set_header        X-Real-IP       $remote_addr;
        proxy_set_header        X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_send_timeout      300;
        proxy_read_timeout      300;
    }
}

nginx 证书

server {
  location / {
  #....
  }
  listen 443 ssl http2;

  ssl_certificate   /path/fullchain.cer; # pem
  ssl_certificate_key /path/cert.key;
  ssl_protocols TLSv1.1 TLSv1.2;
  ssl_ciphers ECDHE-RSA-AES128-GCM-SHA256:HIGH:!aNULL:!MD5:!RC4:!DHE;
  ssl_prefer_server_ciphers on;
  ssl_session_cache shared:SSL:10m;
  ssl_session_timeout 10m;
}

把http请求转发到 https:

server {
  if ($host = xxx.com) {
    return 301 https://$host$request_uri;
  }

  server_name xxx.com;
  listen 80;
  return 404;

}

nginx 负载均衡

#gzip on
upstream node_server{
    server 192.168.0.1:8001 weight=10;
    server 192.168.0.2:8001 weight=20;
}

server{
    listen 80;
    server_name localhost;

    location /{
        proxy_pass http://node_server;
        root html;
        index index.html index.htm;
    }
}

nignx 缓存

# 1. 配置 http
##cache##
proxy_connect_timeout 500;
#跟后端服务器连接的超时时间_发起握手等候响应超时时间
proxy_read_timeout 600;
#连接成功后_等候后端服务器响应的时间_其实已经进入后端的排队之中等候处理
proxy_send_timeout 500;
#后端服务器数据回传时间_就是在规定时间内后端服务器必须传完所有数据
proxy_buffer_size 128k;
#代理请求缓存区_这个缓存区间会保存用户的头信息以供Nginx进行规则处理_一般只要能保存下头信息即可
proxy_buffers 4 128k;
#同上 告诉Nginx保存单个用的几个Buffer最大用多大空间
proxy_busy_buffers_size 256k;
#如果系统很忙的时候可以申请更大的proxy_buffers 官方推荐*2
proxy_temp_file_write_size 128k;
#proxy缓存临时文件的大小
proxy_temp_path /usr/local/nginx/temp;
#用于指定本地目录来缓冲较大的代理请求
proxy_cache_path /usr/local/nginx/cache levels=1:2 keys_zone=cache_one:200m inactive=1d max_size=30g;
#设置web缓存区名为cache_one,内存缓存空间大小为200M,自动清除超过1天没有被访问过的缓存数据,硬盘缓存空间大小30g
include /etc/nginx/conf.d/*.conf;

# 2.location上添加缓存
#静态数据保存时效
location ~ \.html$ {
      proxy_pass https://www.chuchur.com;
      proxy_redirect off;
      proxy_cache cache_one;
      #此处的cache_one必须于上一步配置的缓存区域名称相同
      proxy_cache_valid 200 304 12h;
      proxy_cache_valid 301 302 1d;
      proxy_cache_valid any 1m;
      #不同的请求设置不同的缓存时效
      proxy_cache_key $uri$is_args$args;
      #生产缓存文件的key,通过4个string变量结合生成
      expires 30d;
      #其余类型的缓存时效为30天
      proxy_set_header X-Forwarded-Proto $scheme;
}


#图片等资源缓存30天
location ~ \.(gif|jpg|jpeg|png|bmp|ico)$ {
    root /var/www/img/;
    expires 30d; #支持 时(h)分(s)秒(m)
}
#视频媒体资源永久缓存
location ~ \.(wma|wmv|asf|mp3|mmf|zip|rar|swf|flv)$ {
    root /var/www/upload/;
    expires max;

    #禁止缓存,每次都从服务器请求
    #add_header Cache-Control no-store;
}

此处需要注意 3 点:

  • 1、只有在 proxy_pass 的时候,才会生成缓存,下一次请求执行到 proxy_pass 的时候会判断是否有缓存,如果有则直接读缓存,返回给客户端,不会执行 proxy_pass;如果没有,则执行 proxy_pass,并按照规则生成缓存文件;可以到 nginx 的 cache 文件夹下看是否生成了缓存文件。
  • 2、proxy_set_header Host \$host 这一句可能导致缓存失败,所以不能配置这一句。我在测试的时候遇到了这个问题,不明原理。
  • 3、proxy_pass 使用 upstream 出差,换成域名或 ip 则可行。

**清除缓存** 缓存文件是根据proxy_cache_key` 这个指令生成的,所以找到对应的缓存文件,删除即可

location ~ /purge(/.*) {
    #删除指定缓存区域cache_one的特定缓存文件$1$is_args$args
    proxy_cache_purge cache_one $1$is_args$args;
    #运行本机和10.0.217.0网段的机器访问,拒绝其它所有
    allow           127.0.0.1;
    allow           10.0.217.0/24;
    deny          all;
}

删除缓存用到 proxy_cache_purge 指令。

nignx websocket

location /ws/ {
    proxy_set_header Host $host;
    proxy_http_version 1.1; #必须
    proxy_set_header Upgrade $http_upgrade;#必须
    proxy_set_header Connection "upgrade";#必须
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    ........
}

nginx 防盗链

location ~* \.(gif|jpg|png|jpeg)$ {
    expires     30d;
    valid_referers none blocke *.chuchur.com www.chuchur.com m.chuchur.com *.baidu.com *.google.com;
    if ($invalid_referer) {
        rewrite ^/ https://chuchur.cn/404.jpg;
    }
}
  • ~*.(jpg|gif|swf)\$: 匹配不区分大小写,以.jpg 或.gif 或 .swf 结尾的文件。
  • valid_referers:设置信任的网站,可以正常使用图片。
  • none:浏览器中 refer 为空的情况,就是直接在浏览器访问图片。
  • blocked:浏览器中 refer 不为空的情况,但是值被代理或防火墙删除了,这些值不以http://或 https://开头。
  • 后面的网址或域名:refer 包含相关字符串的网址。
  • if 语句:如果链接的来源域名不在 valid_referers 所列出的列表中, \$invalid_referer 为 1,则执行后面的操作,即进行重写或* 返回 403 页面。

nginx for Vue

server {
    listen       80 default_server;
    listen       [::]:80 default_server;
    server_name  chuchur.com www.chuchur.com;
    location / {
        root ~/www/html;
        index index.html;
        try_files $uri $uri/ /index.html;
    }
}

其他服务器 vue 部署 请参阅 Vue 部署

https

nginx 如何开启 httpshttp2 (传送门)

ningx css 字体的支持,需要修改 mime.types 加入以下代码

application/octet-stream eot;
application/font-sfnt ttf;
application/font-otf otf;
application/font-woff2 woff2;
application/font-woff woff;

如果是跨域的话,还需要做跨域配置

location ~* .(eot|ttf|woff|svg|otf)$ {
  add_header Access-Control-Allow-Origin *;
}

location 优先级

  • [=]模式: location = path,此种模式优先级最高(但要全路径匹配)
  • [^~]模式:location ^~ path,此种模式优先级第二高于正则;
  • [~ or ~]模式:location ~ path,正则模式,优先级第三,[~]正则匹配区分大小写,[~]正则匹配不区分大小写;
  • [path]模式: location path,中间什么都不加,直接跟路径表达式;

    注意:一次请求只能匹配一个 location,一旦匹配成功后,便不再继续匹配其余 location;

隐藏 nignx 版本号

#将Nginx的配置文件中的server_tokens选项值设置为off,如没有该配置项,加上即可。
vim /usr/local/nginx/conf/nginx.conf
...........    #省略内容
    http {
       include       mime.types;
       default_type  application/octet-stream;
       server_tokens     off;    #关闭版本号
............    #省略内容

相关命令

nginx -t #检查查看配置文件路径,其配置是否正确
nginx -s reload # 重启
nginx -s quit #退出
ningx -s stop #停止

常见问题

nginx 读取文件 permission denied ,这种情况直接会导致 404

[error] 17823#17823: *21 open() "/var/www/html/index.html" failed (13: Permission denied), client: 101.228.94.31, server: _

解决办法: 修改 /etc/nginx/nginx.conf:

 # user nginx;
user root;  ##root权限或其他
worker_processes auto;
pid /run/nginx.pid;

connect() failed (111: Connection refused) while connecting to upstream

#proxy_set_header Host $host #注释掉这句

如果反向代理服务器不重写该请求头的话,那么后端真实服务器在处理时会认为所有的请求都来在反向代理服务器,如果后端有防攻击策略的话,那么机器就被封掉了。因>此,在配置用作反向代理的 nginx 中一般会增加两条配置,修改 http 的请求头:

proxy_set_header Host $http_host;
proxy_set_header X-Forward-For $remote_addr;

这里的$http_host$remote_addr 都是 nginx 的导出变量,可以再配置文件中直接使用。如果 Host 请求头部没有出现在请求头中,则$http_host值为空,但是$host 值>为主域名。因此,一般而言,会用$host代替$http_host 变量,从而避免 http 请求中丢失 Host 头部的情况下 Host 不被重写的失误。

内置变量

$arg_name
请求中的的参数名,即“?”后面的 arg_name=arg_value 形式的 arg_name

$args
请求中的参数值

$binary_remote_addr 客户端地址的二进制形式, 固定长度为 4 个字节

$body_bytes_sent
传输给客户端的字节数,响应头不计算在内;这个变量和 Apache 的 mod_log_config 模块中的“%B”参数保持兼容

$bytes_sent
传输给客户端的字节数 (1.3.8, 1.2.5)

$connection
TCP 连接的序列号 (1.3.8, 1.2.5)

$connection_requests
TCP 连接当前的请求数量 (1.3.8, 1.2.5)

$content_length
“Content-Length” 请求头字段

$content_type
“Content-Type” 请求头字段

$cookie_name
cookie 名称

$document_root
当前请求的文档根目录或别名

$document_uri
$uri

$host
优先级如下:HTTP 请求行的主机名>”HOST”请求头字段>符合请求的服务器名

$hostname
主机名

$http_name
匹配任意请求头字段; 变量名中的后半部分“name”可以替换成任意请求头字段,如在配置文件中需要获取 http 请求头:“Accept-Language”,那么将“-”替换为下划线,大写字母替换为小写,形如:$http_accept_language 即可。

$https
如果开启了 SSL 安全模式,值为“on”,否则为空字符串。

$is_args
如果请求中有参数,值为“?”,否则为空字符串。

$limit_rate
用于设置响应的速度限制,详见 limit_rate。

$msec
当前的 Unix 时间戳 (1.3.9, 1.2.6)

$nginx_version nginx 版本

$pid
工作进程的 PID

$pipe
如果请求来自管道通信,值为“p”,否则为“.” (1.3.12, 1.2.7)

$proxy_protocol_addr
获取代理访问服务器的客户端地址,如果是直接访问,该值为空字符串。(1.5.12)

$query_string
$args

$realpath_root
当前请求的文档根目录或别名的真实路径,会将所有符号连接转换为真实路径。

$remote_addr
客户端地址

$remote_port
客户端端口

$remote_user
用于 HTTP 基础认证服务的用户名

$request
代表客户端的请求地址

$request_body 客户端的请求主体
此变量可在 location 中使用,将请求主体通过 proxy_pass, fastcgi_pass, uwsgi_pass, 和 scgi_pass 传递给下一级的代理服务器。

$request_body_file
将客户端请求主体保存在临时文件中。文件处理结束后,此文件需删除。如果需要之一开启此功能,需要设置 client_body_in_file_only。如果将次文件传递给后端的代理服务器,需要禁用 request body,即设置

proxy_pass_request_body off;
fastcgi_pass_request_body off;
uwsgi_pass_request_body off #or scgi_pass_request_body off

$request_completion
如果请求成功,值为”OK”,如果请求未完成或者请求不是一个范围请求的最后一部分,则为空。

$request_filename
当前连接请求的文件路径,由 rootalias 指令与 URI 请求生成。

$request_length
请求的长度 (包括请求的地址, http 请求头和请求主体) (1.3.12, 1.2.7)

$request_method
HTTP 请求方法,通常为“GET”或“POST”

$request_time
处理客户端请求使用的时间 (1.3.9, 1.2.6); 从读取客户端的第一个字节开始计时。

$request_uri
这个变量等于包含一些客户端请求参数的原始 URI,它无法修改,请查看$uri 更改或重写 URI,不包含主机名,例如:”/cnphp/test.php?arg=freemouse”

$scheme
请求使用的 Web 协议, “http”“https”

$sent_http_name
可以设置任意 http 响应头字段; 变量名中的后半部分“name”可以替换成任意响应头字段,如需要设置响应头 Content-length,那么将“-”替换为下划线,大写字母替换为小写,形如:$sent_http_content_length 4096 即可。

$server_addr
服务器端地址,需要注意的是:为了避免访问 linux 系统内核,应将 ip 地址提前设置在配置文件中。

$server_name
服务器名,www.cnphp.info

$server_port
服务器端口

$server_protocol
服务器的 HTTP 版本, 通常为 “HTTP/1.0”“HTTP/1.1”

$status
HTTP 响应代码 (1.3.2, 1.2.2)

$tcpinfo_rtt, $tcpinfo_rttvar, $tcpinfo_snd_cwnd, $tcpinfo_rcv_space
客户端 TCP 连接的具体信息

$time_iso8601
服务器时间的 ISO 8610 格式 (1.3.12, 1.2.7)

$time_local
服务器时间(LOG Format 格式) (1.3.12, 1.2.7)

$uri
请求中的当前 URI(不带请求参数,参数位于$args),可以不同于浏览器传递的$request_uri 的值,它可以通过内部重定向,或者使用 index 指令进行修改,$uri 不包含主机名,如”/foo/bar.html”

常见问题

Active: inactive (dead)

sudo systemctl enable nginx.service
sudo systemctl start nginx.service
sudo systemctl status nginx.service

我,秦始皇,打钱!

相关文章

禅境花园小程序

关注前沿技术开发.