Nginx基础学习

编译安装

wget http://nginx.org/download/nginx-1.16.0.tar.gz
tar zxf nginx-1.16.0
./configure --prefix=/usr/local/nginx

需要环境:
HTTP rewrite: pcre pcre-devel
HTTP gzip: zlib zlib-devel
make && make install

nginx目录结构

–conf 配置文件
–html 网站目录
–logs 日志文件

—建议每个网站的日志文件分开存放(比如放在网站的logs目录下)

–sbin 主要的二进制文件

启动

cd /usr/local/nginx
./sbin/nginx

如果以前安装了其他的服务器软件,可能会出现端口被占用,导致无法启动
关掉占用端口的程序:

netstat -antp # 查看端口使用情况
pkill -9 XXX  # 杀掉这个进程

(如果提示没有netstat命令,用yum search netstat 查看这个命令在哪个包里,安装即可)

工作情况

一个主进程,控制着n个工作进程来处理用户的请求
当收到用户的请求,主进程把请求交给一个空闲的工作进程来处理

查看nginx进程信息:

[root@localhost nginx]# ps -aux | grep nginx
root     18728  0.0  0.0  20552   804 ?        Ss   09:39   0:00 nginx: master process sbin/nginx
nobody   18729  0.0  0.1  21004  1328 ?        S    09:39   0:00 nginx: worker process
root     23516  0.0  0.0 112724   996 pts/0    R+   10:14   0:00 grep --color=auto nginx

可以看到当前有一个主进程和一个工作进程

信号量

命令格式:
nginx -s signal
signal可以为:

stop  # 快速关闭nginx --- kill -INT `cat ./logs/nginx.pid`
quit  # 优雅地关闭nginx(等待nginx处理完所有请求后关闭) --- kill -QUIT `cat ./logs/nginx.pid`
reload  # 重新载入配置文件 --- kill -HUP `cat ./logs/nginx.pid`
reopen  # 重新打开日志文件 --- kill -USR1 `cat ./logs/nginx.pid`

虚拟主机配置

nginx.conf

#user  nobody;
worker_processes  1;                   # 工作子进程数量,一般设置为cpu核数*4

#error_log  logs/error.log;
#error_log  logs/error.log  notice;
#error_log  logs/error.log  info;

#pid        logs/nginx.pid;

                                       # 配置nginx进程和连接的特性 
events {
    worker_connections  1024;          # 一个work进程能最大支持多少个连接
}

                                       # 配置 http 服务的主要段
http {
    include       mime.types;
    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;

    sendfile        on;
    #tcp_nopush     on;

    #keepalive_timeout  0;
    keepalive_timeout  65;

    #gzip  on;
    
    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$ {
        #    root           html;
        #    fastcgi_pass   127.0.0.1:9000;
        #    fastcgi_index  index.php;
        #    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;
        #}
    }
}

worker_processes 工作子进程数量

events段 配置nginx进程与连接的属性
– worker_connections 一个work进程最大支持多少个连接

http段 配置http服务
– server段 配置虚拟主机

最简单的server配置

server {
    listen 80;
    server_name 127.0.0.1;
    
    location / {
        root /usr/local/nginx/html/test1;
        inde index.html;
    }
}
server {
    listen 8080;
    server_name 127.0.0.1;
    
    location / {
        root /usr/local/nginx/html/test2
    }
}

这样配置两个server_name一样,端口不同的server段,可以实现基于端口的访问方式

日志管理

nginx允许对不同的server进行不同的log管理,也可以全局配置

日志类型:访问日志、错误日志

定义方式:access_log (error_log) 日志存放路径 日志格式
如:
在server段内配置

server {
    ......
    access_log  logs/host.access.log  main;
    ......
}

在http段内配置

http {
    ......
    access_log  logs/access.log  main;
    ......
}

日志格式 — main

log_format  main  '$remote_addr - $remote_user [$time_local] "$request"'
                  '$status $body_bytes_sent "$http_referer"'
                  '"$http_user_agent" "$http_x_forwarded_for"';
参数意思
$remote_addr远程访问IP
$remote_user用户信息(在http请求中携带,没携带就没有)
$time_local用户本地时间
$request请求信息
$status状态码
$body_bytes_sent请求主体的字节数
$http_referer上一个页面来自哪里(可以用来做图片的防盗链)
$http_user_agent用户代理(浏览器)
$http_xforwarded_for最后一次代理服务器的IP

蜘蛛协议(搜索引擎协议) robots.txt ,定义哪些可以爬,哪些不能爬,只是一种规范,可以不遵守。
把robots.txt放在网站的根目录,当蜘蛛爬到这个网站的时候,就根据这个文件定义的方式来爬取。
如果没有这个文件,那么就把这个网站都爬了。
格式:
User_agent: Baiduspider
Disallow: /admin

切割日志

date "+%Y-%m-%d %H:%M:%S"  # 年-月-日 时:分:秒

参数:
%Y 年
%m 月
%d 日
%H 时(24小时制)
%I 时(12小时制)
%M 分
%S 秒
%j 今天是这一年中的第几天

date -s "20181212 12:15:45" 设置当前时间

date "+%Y%m%d" 格式化输出当前时间

location

  1. 三种匹配模式:精准、普通、正则。
  2. 匹配优先级:精准 > 普通 > 正则
  3. 使用优先级:精准 > 正则 > 普通

精准

location = /index.html {
	root /var/www/html/;
    index index.html index.php
}

普通

location /image {
	root /var/www/html/;
    index index.html index.php
}

正则

location ~ (.*?).php(.*/) {
	root /var/www/html/;
    index index.html index.php
}

重写

格式

if (条件) {
	set # 设置变量
	return # 返回状态码
	break #跳出
	rewrite #重写
}
条件:
1.“=”,字符串比较
2.“~”,用正则匹配(区分大小写)
3.“~*”,不区分大小写的正则
4.-f -d -e,判断是否为文件、目录、存在
\# 用 = 条件屏蔽ip
if ($remote_addr = 192.168.1.12) {
	return 403;
}

\# 用正则条件
if ($http_user_agent ~* msie) {
	return 403;
}

\# rewrite
if (!-e $document_root$fastcgi_script_name) {
	rewrite ^.*& /404.html break;
}

\# set 设置一个变量
\# 如果不是IE,并且不是访问ie.html,则重定向到ie.html
if ($http_user_agent ~* msie) {
	set $isRewrite 1;
}
if ($fastcgi_script_name = ie.html) {
	set $isRewrite 0;
}
if ($isRewrite = 1) {
	rewrite ^.*& ie.html;
}

利用重写可以实现伪静态路由

比如请求url:http://www.test.com/32154.html

在nginx中重写

location ~ \d+\.html& {
	rewrite (\d+)\.html /index.php?id=$1;
}

实际访问的是http://www.test.com/index.php?id=32154

gzip压缩

在浏览器的请求头可以看到access-encoding字段,表示浏览器可以支持的压缩算法,一般有gzip、deflate、br

在Nginx开启gzip的常用参数

gzip on|off		# 是否开启gzip
gzip_buffers 32 4K|16 8K # 缓冲(压缩在内存中国缓冲几块?每块多大)
gzip_comp_level [1-9] # 压缩级别,越高越小,越浪费cpu,建议6
gzip_disable # 正则匹配UA,什么UA不进行gzip
gzip_min_length 200 # 进行压缩的最小长度(单位B),小于这个长度就不进行压缩
gzip_http_version 1.0|1.1 #开始进行压缩的http版本,小于这个版本的就不惊醒压缩
gzip_proxied	# 设置请求者代理服务器,该如何缓存内容(小的web应用一般不用代理)
gzip_types text/plain application/xml # 对哪些类型的文件进行压缩,text、xml、js、css等等,html类型默认压缩,不用填(可以在nginx/conf/mime.types中看每个类型怎么写)
gzip_vary on|off	# 是否传送压缩标志,告诉对方这是gzip压缩过的

开启gzip的基本配置

gzip on;
gzip_buffers 32 4K;
gzip_comp_level 6;
gzip_min_length 200;
gzip_types text/css text/xml application/javascript text/plain

expires设置过期时间

让文件在浏览器中存放一段时间

在location或if中写

location{
	expires 30s; # 30秒过期,m分钟,h小时,d天
}

当浏览器再次访问nginx的时候,如果文件还没过期,nginx会返回304

304是一种很好的缓存机制

原理:服务器响应时,同时发送etag标签(内容的签名,内容改变etag也会变)和last_modified_since两个值。浏览器下次请求时,头信息也会发送这两个值,服务器根据这两个值去判断文件是否发生改变,如过没有,则返回304

Nginx+Apache反向代理

反向代理:将请求转到其他服务器处理,处理完后把结果拿回来发送回给客户端

动静分离:就是反向代理,一台服务处理静态页面,另一台服务器处理动态页面

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-xrmBfAbd-1573808579122)(./image/反向代理.png)]

Nginx配置,遇到.php的时候,不处理,而是转发给Apache监听的端口

location ~ .php$ {
    proxy_pass http://127.0.0.1:8888;
}

如果想用负载均衡转发到多个服务器,使用upstream指令,声明一个组

**注意:**server 要用IP或远程主机名,不能用localhost

格式:

upstream 组名 {
    server 主机名 参数;
    ...
    [其他语句]
}
server语句常用参数:
weight=1 权重,权重越大,优先级越高
fail_timeout=3 超时时间(s)
max_fails=3 最大失败次数,超过之后就把这个服务器当做不可达
backup 表示这个服务器时后备服务器,当主要的服务器都无效时启用
down 标识这个服务器永久无效

比如声明一个处理php的服务器组

upstream phpServer {
    server 127.0.0.1:8888 weight=2 fail_timeout=3 max_fails=3;
    server 127.0.0.2:8889 weight=1 fail_timeout=3 max_fails=3;
}
location ~ \.php$ {
    proxy_pass http://phpServer;
}

Nginx连接Memcache

location / {
    set $memcache_key "$uri?args";
    memcached_pass 127.0.0.1:11211;
    error_page /callback.php;
}

如果要多台服务器负载均衡,需要安装第三方模块ngx_http_upstream_consistent_hash 来实现一致性hash 模块 官网

源码git地址:https://github.com/replay/ngx_http_consistent_hash

编译第三方模块需要在配置编译参数时写上–add-module参数指定第三方模块的源码地址,如:

./configure --prefix=/usr/local/nginx --add-module=/usr/local/src/ngx_http_consistent_hash-master

使用方法:直接在upstream里面写上consistent_hash key

upstream mcServer {
    consistent_hash $request_uri;
    server 127.0.0.1:11211;
    server 127.0.0.1:11212;
    server 127.0.0.1:11213;
}

location / {
    set $memcache_key $request_uri;
    memcached_pass mcServer;
    error_page /callback.php;
}

在Nginx使用了一致性hash,服务端语言也要使用一致性hash来选择memcache服务器

在php中,安装了memcache扩展后,可以在php.ini中配置memcache使用一致性hash算法。添加 memcache.hash_strategy = consistent 到php.ini中,设置映射策略。详细查看https://www.php.net/manual/zh/memcache.ini.php

持续更新。。。。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值