NGINX_01

常用命令

1
2
3
4
5
6
7
8
nginx -s stop       #快速关闭Nginx,可能不保存相关信息,并迅速终止web服务。
nginx -s quit #平稳关闭Nginx,保存相关信息,有安排的结束web服务。
nginx -s reload #因改变了Nginx相关配置,需要重新加载配置而重载。
nginx -s reopen #重新打开日志文件。
nginx -c filename #为 Nginx 指定一个配置文件,来代替缺省的。
nginx -t #不运行,而仅仅测试配置文件。nginx 将检查配置文件的语法的正确性,并尝试打开配置文件中所引用到的文件。
nginx -v #显示 nginx 的版本。
nginx -V #显示 nginx 的版本,编译器版本和配置参数。

nginx 启动脚本

使用 service nginxd start 的方式启动

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
#!/bin/bash

#@version: 0.0.1
#@author: lifafu
#@file:
#@time: 2017/02/04 08:00
#@company:

source /etc/profile #加载系统环境变量
source $HOME/.bash_profile #加载用户环境变量
#set -o nounset #引用未初始化变量时终止执行,也可以set -u
#set -o errexit #执行任何语句返回非0状态时终止执行,也可以set -e

# chkconfig: - 99 50
# 虽然前面带#号,是注释,但要用chkconfig命令注册开机启动服务器的话,该句必不可少,格式也不能错!
# 3个chkconfig参数的含义:
# x:是指定该脚本在哪个系统启动级别下运行,比如你需要在3,4,5上运行,那么第二位就设置成345,我这里用的是”-”,代表在2,3,4,5上都运行
# y:系统启动时,服务启动顺序,需要注意的是,有的程序依赖与别的程序的话,启动顺序就要注意了,比如A程序的启动依赖于B程序的启动,那么A程序的这个值一定要比B程序大
# z:系统终止时,服务终止顺序

# description: Nginx is a high-performance web and proxy server.
# 该句也必不可少,理由同上,你程序的描述和简介,而非本启动脚本

#设置变量
nginxd=/usr/local/nginx/sbin/nginx
nginx_config=/usr/local/nginx/conf/nginx.conf
nginx_pid=/usr/local/nginx/logs/nginx.pid
nginx_lock=/var/lock/subsys/nginx

#保存退出状态的变量,初始值为0(在linux一般0表示成功,表示OK,非0表示异常,不OK)
RETYAL=0

# 设置程序名称
prog="nginx"

# Source function library.在当前shell中运行的函数库文件
# 在functions中定义了很多函数,在这里可以调用,系统提供的函数文件,这里面实现了很多函数和环境变量,比如start的时候,红色的字显示OK就是这个文件的功劳
. /etc/rc.d/init.d/functions

# Source network configuration.加载网络配置
. /etc/sysconfig/network

# Check that networking is up.
[ ${NETWORKING} = "no" ] && exit 0

# 定义启动函数
start() {
# 判断程序是否存在,否则异常退出
[ -x $nginxd ] || { echo “FATAL: No such programme”;exit 4; }

# 判断配置文件是否存在,否则异常退出
[ -f $nginx_config ] || { echo “FATAL:Config file does not exist”;exit 6; }

# 判断程序是否运行,否则异常退出
if [ -e $nginx_pid ];then
echo "nginx already running...."
exit 1
fi

# 判断lock文件是否存在,否则异常退出
if [ -e $nginx_lock ];then
echo "nginx lock file does exist...."
exit 1
fi

# 显示信息,依赖于. /etc/rc.d/init.d/functions
echo -n $"Starting $prog:"

# 创建pid文件夹
dir=$(dirname $nginx_pid)
[ -d $dir ] || mkdir -p $dir

# 调用functions里的daemon函数来启动nginx,daemon()函数主要用于希望脱离控制台,以守护进程形式在后台运行的程序
daemon --pidfile $nginx_pid $nginxd -c ${nginx_config}

# 把daemon函数调用的结果保存到RETVAL里
RETVAL=$?
echo

# 判断RETVALR值,如果是0执行成功,则生成锁文件,锁文件主要用来判断程序是否运行
[ $RETVAL = 0 ] && touch $nginx_lock

#终止函数,并返回$RETVAL的值,通常用于函数的结束, 本身这段代码也是个函数,所以我们也要返回,返回RETVAL的值
return $RETVAL
}


# 定义停止函数
stop() {
echo -n $"Stoping $prog:"

#killproc也在. /etc/rc.d/init.d/functions里面定义
killproc -p $nginx_pid $prog
RETVAL=$?
echo
[ $RETVAL = 0 ] && rm -f $nginx_lock $nginx_pid
}

reload() {
echo -n $"Reloading $prog:"
#kill -HUP `cat ${nginx_pid}`
killproc -p $nginx_pid $prog -HUP
RETVAL=$?
echo
}

#See how we were called.
case "$1" in
start)
start
;;
stop)
stop
;;
reload)
reload
;;
restart)
stop
start
;;
#status在. /etc/rc.d/init.d/functions里有定义
status)
status $prog
RETVAL=$?
;;
#输入其他内容提示以下内容
*)
echo $"Usage:$prog{start|stop|restart|reload|status|help}"
exit 1
esac
exit $RETVAL

HTTP反向代理配置

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
#运行用户
#user somebody;

#启动进程,通常设置成和cpu的数量相等
worker_processes 1;

#全局错误日志
error_log D:/Tools/nginx-1.10.1/logs/error.log;
error_log D:/Tools/nginx-1.10.1/logs/notice.log notice;
error_log D:/Tools/nginx-1.10.1/logs/info.log info;

#PID文件,记录当前启动的nginx的进程ID
pid D:/Tools/nginx-1.10.1/logs/nginx.pid;

#工作模式及连接数上限
events {
worker_connections 1024; #单个后台worker process进程的最大并发链接数
}

#设定http服务器,利用它的反向代理功能提供负载均衡支持
http {
#设定mime类型(邮件支持类型),类型由mime.types文件定义
include D:/Tools/nginx-1.10.1/conf/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 D:/Tools/nginx-1.10.1/logs/access.log main;
rewrite_log on;

#sendfile 指令指定 nginx 是否调用 sendfile 函数(zero copy 方式)来输出文件,对于普通应用,
#必须设为 on,如果用来进行下载等应用磁盘IO重负载应用,可设置为 off,以平衡磁盘与网络I/O处理速度,降低系统的uptime.
sendfile on;
#tcp_nopush on;

#连接超时时间
keepalive_timeout 120;
tcp_nodelay on;

#gzip压缩开关
#gzip on;

#设定实际的服务器列表
upstream zp_server1{
server 127.0.0.1:8089;
}

#HTTP服务器
server {
#监听80端口,80端口是知名端口号,用于HTTP协议
listen 80;

#定义使用www.xx.com访问
server_name www.helloworld.com;

#首页
index index.html

#指向webapp的目录
root D:\01_Workspace\Project\github\zp\SpringNotes\spring-security\spring-shiro\src\main\webapp;

#编码格式
charset utf-8;

#代理配置参数
proxy_connect_timeout 180;
proxy_send_timeout 180;
proxy_read_timeout 180;
proxy_set_header Host $host;
proxy_set_header X-Forwarder-For $remote_addr;

#反向代理的路径(和upstream绑定),location 后面设置映射的路径
location / {
proxy_pass http://zp_server1;
}

#静态文件,nginx自己处理
location ~ ^/(images|javascript|js|css|flash|media|static)/ {
root D:\01_Workspace\Project\github\zp\SpringNotes\spring-security\spring-shiro\src\main\webapp\views;
#过期30天,静态文件不怎么更新,过期可以设大一点,如果频繁更新,则可以设置得小一点。
expires 30d;
}

#设定查看Nginx状态的地址
location /NginxStatus {
stub_status on;
access_log on;
auth_basic "NginxStatus";
auth_basic_user_file conf/htpasswd;
}

#禁止访问 .htxxx 文件
location ~ /\.ht {
deny all;
}

#错误处理页面(可选择性配置)
#error_page 404 /404.html;
#error_page 500 502 503 504 /50x.html;
#location = /50x.html {
# root html;
#}
}
}

注意启动绑定的端口要和nginx中的upstream设置的端口保持一致。

负载均衡配置

网站在实际运营过程中,多半都是有多台服务器运行着同样的 app,这时需要使用负载均衡来分流

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
http {
#设定mime类型,类型由mime.type文件定义
include /etc/nginx/mime.types;
default_type application/octet-stream;
#设定日志格式
access_log /var/log/nginx/access.log;

#设定负载均衡的服务器列表
upstream load_balance_server {
#weigth参数表示权值,权值越高被分配到的几率越大
server 192.168.1.11:80 weight=5;
server 192.168.1.12:80 weight=1;
server 192.168.1.13:80 weight=6;
}

#HTTP服务器
server {
#侦听80端口
listen 80;

#定义使用www.xx.com访问
server_name www.helloworld.com;

#对所有请求进行负载均衡请求
location / {
root /root; #定义服务器的默认网站根目录位置
index index.html index.htm; #定义首页索引文件的名称
proxy_pass http://load_balance_server ;#请求转向load_balance_server 定义的服务器列表

#以下是一些反向代理的配置(可选择性配置)
#proxy_redirect off;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
#后端的Web服务器可以通过X-Forwarded-For获取用户真实IP
proxy_set_header X-Forwarded-For $remote_addr;
proxy_connect_timeout 90; #nginx跟后端服务器连接超时时间(代理连接超时)
proxy_send_timeout 90; #后端服务器数据回传时间(代理发送超时)
proxy_read_timeout 90; #连接成功后,后端服务器响应时间(代理接收超时)
proxy_buffer_size 4k; #设置代理服务器(nginx)保存用户头信息的缓冲区大小
proxy_buffers 4 32k; #proxy_buffers缓冲区,网页平均在32k以下的话,这样设置
proxy_busy_buffers_size 64k; #高负荷下缓冲大小(proxy_buffers*2)
proxy_temp_file_write_size 64k; #设定缓存文件夹大小,大于这个值,将从upstream服务器传

client_max_body_size 10m; #允许客户端请求的最大单文件字节数
client_body_buffer_size 128k; #缓冲区代理缓冲用户端请求的最大字节数
}
}
}

多服务配置

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
http {
#此处省略一些基本配置

upstream product_server{
server www.helloworld.com:8081;
}

upstream admin_server{
server www.helloworld.com:8082;
}

upstream finance_server{
server www.helloworld.com:8083;
}

server {
#此处省略一些基本配置
#默认指向product的server
location / {
proxy_pass http://product_server;
}

location /product/{
proxy_pass http://product_server;
}

location /admin/ {
proxy_pass http://admin_server;
}

location /finance/ {
proxy_pass http://finance_server;
}
}
}

HTTPS反向代理配置

  • HTTPS 的固定端口号是 443,不同于 HTTP 的 80 端口

  • SSL 标准需要引入安全证书,所以在 nginx.conf 中你需要指定证书和它对应的 key
    其他和 http 反向代理基本一样,只是在 server 部分配置有些不同

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    #HTTP服务器
    server {
    #监听443端口。443为知名端口号,主要用于HTTPS协议
    listen 443 ssl;

    #定义使用www.xx.com访问
    server_name www.helloworld.com;

    #ssl证书文件位置(常见证书文件格式为:crt/pem)
    ssl_certificate cert.pem;
    #ssl证书key位置
    ssl_certificate_key cert.key;

    #ssl配置参数(选择性配置)
    ssl_session_cache shared:SSL:1m;
    ssl_session_timeout 5m;
    #数字签名,此处使用MD5
    ssl_ciphers HIGH:!aNULL:!MD5;
    ssl_prefer_server_ciphers on;

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

    静态站点配置

    有时候,我们需要配置静态站点(即 html 文件和一堆静态资源)
    比如本博客的技术栈,使用了Hexo作为博客的搭建工具,所有的静态资源都放在了 **/public目录下,我们只需要在 nginx.conf 中指定首页以及这个站点的 host 即可

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    worker_processes  1;

    events {
    worker_connections 1024;
    }

    http {
    include mime.types;
    default_type application/octet-stream;
    sendfile on;
    keepalive_timeout 65;

    gzip on;
    gzip_types text/plain application/x-javascript text/css application/xml text/javascript application/javascript image/jpeg image/gif image/png;
    gzip_vary on;

    server {
    listen 80;
    server_name yunzilla.com;

    location / {
    root /opt/hexo/public;
    index index.html;
    #转发任何请求到 index.html
    }
    }
    }

    搭建文件服务器

    使用 Nginx 可以非常快速便捷的搭建一个简易的文件服务。
    配置要点:

  • 将 autoindex 开启可以显示目录,默认不开启。

  • 将 autoindex_exact_size 开启可以显示文件的大小。

  • 将 autoindex_localtime 开启可以显示文件的修改时间。

  • root 用来设置开放为文件服务的根路径。

  • charset 设置为 charset utf-8,gbk;,可以避免中文乱码问题

1
2
3
4
5
6
7
8
9
10
11
autoindex on;# 显示目录
autoindex_exact_size on;# 显示文件大小
autoindex_localtime on;# 显示文件时间

server {
charset utf-8,gbk; # windows 服务器下设置后,依然乱码,暂时无解
listen 9050 default_server;
listen [::]:9050 default_server;
server_name _;
root /share/fs;
}

跨域

解决跨域问题一般有两种思路:
CORS
在后端服务器设置 HTTP 响应头,把你需要运行访问的域名加入加入 Access-Control-Allow-Origin中。
JSONP
把后端根据请求,构造** json** 数据,并返回,前端用 jsonp 跨域。
Nginx 根据第一种思路,也提供了一种解决跨域的解决方案

  1. 首先,在 **enable-cors.conf **文件中设置 cors :
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    # allow origin list
    set $ACAO '*';

    # set single origin
    if ($http_origin ~* (www.helloworld.com)$) {
    set $ACAO $http_origin;
    }

    if ($cors = "trueget") {
    add_header 'Access-Control-Allow-Origin' "$http_origin";
    add_header 'Access-Control-Allow-Credentials' 'true';
    add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
    add_header 'Access-Control-Allow-Headers' 'DNT,X-Mx-ReqToken,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type';
    }

    if ($request_method = 'OPTIONS') {
    set $cors "${cors}options";
    }

    if ($request_method = 'GET') {
    set $cors "${cors}get";
    }

    if ($request_method = 'POST') {
    set $cors "${cors}post";
    }
  2. 接下来,在你的服务器中** include enable-cors.conf** 来引入跨域配置:
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    # ----------------------------------------------------
    # 此文件为项目 nginx 配置片段
    # 可以直接在 nginx config 中 include(推荐)
    # 或者 copy 到现有 nginx 中,自行配置
    # www.helloworld.com 域名需配合 dns hosts 进行配置
    # 其中,api 开启了 cors,需配合本目录下另一份配置文件
    # ----------------------------------------------------
    upstream front_server{
    server www.helloworld.com:9000;
    }
    upstream api_server{
    server www.helloworld.com:8080;
    }

    server {
    listen 80;
    server_name www.helloworld.com;

    location ~ ^/api/ {
    include enable-cors.conf;
    proxy_pass http://api_server;
    rewrite "^/api/(.*)$" /$1 break;
    }

    location ~ ^/ {
    proxy_pass http://front_server;
    }
    }

** THE END.**

Author

Yunzilla

Posted on

2021-09-02

Updated on

2021-09-13

Licensed under

Comments