Nginx使用总结
下载与安装
下载地址:
wget https://mirrors.huaweicloud.com/nginx/nginx-1.25.3.tar.gz
有的Linux机器需要安装gcc的依赖,使用下面的命令
yum install zlib zlib-devel openssl openssl-devel pcre pcre-devel
yum install gcc-c++
yum install make
最简单的编译安装
tar –zxvf nginx-1.25.3.tar.gz
cd nginx-1.25.3.tar.gz
./configure --prefix=/home/yauser/app/nginx-1.25.3
make install
prefix为编译后可执行程序的路径,编译后是哪个路径即便复制到其他路径,程序日志等相关的文件依然会放到这里
安装其他非官网提供的模块
打补丁,这里以安装阿里巴巴主动检查模块为例:
wget https://codeload.github.com/yaoweibin/nginx_upstream_check_module/zip/master
cd nginx源码路径
patch -p1 < 补丁包路径/check_1.20.1+.patch
编译:
./configure --user=root --group=root --prefix=编译后的路径 --with-http_ssl_module --add-module=/补丁包的路径
make && make install
其中–with-http_ssl_module为nginx提供的模块但额外安装
–add-module 为第三方模块
常用命令
启动:
nginx –c <Nginx的配置文件,必须是全路径>
停止
./nginx –s stop
重启(有些配置文件的更改必须停止后启动)
./nginx –s reload
基础配置
worker_processes 配置为与机器物理核数保持一致
解决html乱码
http块下新增charset UTF-8;
post请求太大需要使用临时文件的配置:
# 设置客户端请求体的最大大小为100M
client_max_body_size 100M;
proxy_connect_timeout 300s;
proxy_send_timeout 300s;
proxy_buffer_size 1024k;
proxy_buffers 16 1024k;
proxy_busy_buffers_size 2048k;
proxy_temp_file_write_size 2048k;
fastcgi_buffer_size 1024;
fastcgi_buffers 16 1024k;
http协议升级为websocket协议:
map $http_upgrade $connection_upgrade {
default upgrade;
'' close;
}
配置负载均衡
在http块下新增
upstream saas {
server ip地址加端口号;
}
配置访问日志
需要再http块下新增
log_format main '$remote_addr $remote_user $time_local $request $http_host $status $upstream_status $body_bytes_sent $http_referer $http_user_agent $http_cookie $upstream_addr $request_time $upstream_response_time';
# 声明访问日志记录的路径
access_log /opt/jenkins/software/nginx-1.25.3/logs/access.log main;
路径匹配规则
符合则终止搜索
# 匹配静态资源,不符合的继续搜索
location ~* \.(gif|jpg|jpeg|css|js)$ {
proxy_pass http://saas$request_uri;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
不符合则继续搜索
# 匹配静态资源,不符合的继续搜索
location ~* \.(gif|jpg|jpeg|css|js)$ {
proxy_pass http://saas$request_uri;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
匹配/开头的地址
这个优先级最低
location / {
proxy_pass http://saas$request_uri;
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_set_header Cookie $http_cookie;
}
常用的取值语法
设置代理地址
proxy_pass http://saas$request_uri;
$request_uri为请求的uri
设置header头
proxy_set_header header的名字 Value
取一些客户端的http header
$http_cookie
$http_Authorization
nginx 自身的取值
# 协议升级:
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection $connection_upgrade;
# 协议
proxy_redirect http:// $scheme://;
# 远程IP和地址
proxy_set_header X-real-ip $remote_addr;
proxy_set_header X-Forwarded-For $remote_addr;
proxy_set_header Host $host;