nginx学习笔记

2.6k words

常用command

nginx -v #检查版本
service nginx status #运行检查
mv <> <> #重命名文件
touch <> #创建文件
nginx -t #检查config
nginx -s reload #重加载配置

config

cd /etc/nginx #重要文件夹
mime.types #文件后缀对应,引入conf
nginx.conf #重要配置文件
/conf.d #


default.conf

将conf转入conf.d文件夹内方便管理
nginx.conf需要

1
2
3
4
5
6
7
8
9
10
#重要结构
events {}


http { #http协议块头

include /etc/nginx/mime.types; #引入文件
include /etc/nginx/conf.d/*.conf; #匹配conf.d下属conf文件

}

*.conf示例

1
2
3
4
5
6
7
8
9
10
11
12

server {
listen 80; #监听端口
server_name dm.dm 127.0.0.1 localhost; #监听域名地址


root /var/www/file; #网站根目录
index index.html; #指定默认文件

return 200 "good"; #返回
}

基础块使用

配置文件location代码块匹配

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
  server {
listen 80; #监听端口
server_name dm.dm 127.0.0.1 localhost; #监听域名地址
root /var/www/localhost; #网站根目录
location /app {
root /var/www/localhost; #网站根目录
}

}

#此处location为匹配规则,全部为location <可选参数> /app默认正则
如果访问http://127.0.0.1/app 不行,因为访问的是/app文件
需要访问http://127.0.0.1/app/
或者http://127.0.0.1/appppa/index.html location会匹配开头app关键词,并向下逐级寻找'index'
如果需要完全一致匹配,则location = /app

正则匹配参数:
= #精确
^~ #优先前缀
~ #正则
<speace> #普通前缀


return 307重定向
示例:

1
2
3
4
5
6
7
8
9
10
11
12
server {
listen 80; #监听端口
server_name dm.dm 127.0.0.1 localhost; #监听域名地址
root /var/www/localhost; #网站根目录
location /app {
return 307 /index/index.html; #显式重定向

}

}


rewrite 改写路径
示例:

1
2
3
4
5
6
7
8
server {
listen 80; #监听端口
server_name dm.dm 127.0.0.1 localhost; #监听域名地址
root /var/www/localhost; #网站根目录

rewrite /app /index/index.html; #/app to /index/index.html 不改写url
}

try_files 和 error_page
示例:

1
2
3
4
5
6
7
8
9
10
11
12
13
server {
listen 80; #监听端口
server_name dm.dm 127.0.0.1 localhost; #监听域名地址
root /var/www/localhost; #网站根目录
index index.html;
error_page 404 /404.html; #自定义404(可以是别的error码)页面

location / {
try_files $url $url/ =404; #访问http://localhost/app 匹配$url也就是/app,访问http://localhost/app/ 则向下按照location检索index,如果都没有则返回404error
}

}

proxy_pass
访问/page1反代给http://dmhy.org示例:

1
2
3
4
5
6
7
8
9
10
11
12
server {
listen 80; #监听端口
server_name dm.dm 127.0.0.1 localhost; #监听域名地址
root /var/www/localhost; #网站根目录
index index.html
error_page 404 /404.html; #自定义404(可以是别的error码)页面

location /page1 {
procy_pass http://dmhy.org;
}

}

负载均衡

实现需要设置upstream块在http块内,server块外
由于我们在nginx.conf内的http块里面引用conf.d文件夹内conf,所以*.conf在server块写upstream块即可
示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
upstream backend-servers {  #设置上游服务器集群name(如backend-servers)
server localhost:3000 weight=1;
server localhost:3001 weight=1; #服务器集群各个地址weight=<数值越大分配越多>

}

server {
listen 80; #监听端口
server_name dm.dm 127.0.0.1 localhost; #监听域名地址
root /var/www/localhost; #网站根目录
index index.html
error_page 404 /404.html; #自定义404(可以是别的error码)页面

location /page1 {
procy_pass http://backend-servers; #对/page1的流量分流给upstream backend-servers
}

}