• 技术文章 >运维 >Nginx

    浅析nginx的安装与使用(收藏)

    奋力向前奋力向前2021-09-01 11:13:39转载429

    之前的文章《深入浅出了解Linux和MacOS终端大小写敏感问题(附代码)》中,给大家了解了Linux和MacOS终端大小写敏感问题。下面本篇文章给大家了解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-sreload#重启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负载均衡

    #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 点:

    **清除缓存** 缓存文件是根据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_referer1,则执行后面的操作,即进行重写或*返回 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部署请参阅的地址:https://router.vuejs.org/zh/guide/essentials/history-mode.html#%E5%90%8E%E7%AB%AF%E9%85%8D%E7%BD%AE%E4%BE%8B%E5%AD%90

    https

    nginx如何开启httpshttp2(传送门

    ningxcss字体的支持,需要修改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优先级

    隐藏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

    传输给客户端的字节数,响应头不计算在内;这个变量和Apachemod_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

    推荐学习:Nginx视频教程PHP视频教程

    以上就是浅析nginx的安装与使用(收藏)的详细内容,更多请关注php中文网其它相关文章!

    声明:本文转载于:禅境花园,如有侵犯,请联系admin@php.cn删除
    专题推荐:nginx
    上一篇:nginx启动命令是什么 下一篇:浅析nginx的缓存和清理(代码分享)
    线上培训班

    相关文章推荐

    • nginx为什么不支持php• nginx不能运行php文件怎么办• nginx 没有解析php怎么办• nginx php 图片不显示怎么办• mac nginx不解析php怎么办

    全部评论我要评论

  • 取消发布评论发送
  • 1/1

    PHP中文网