返回总目录页

nginx 常见配置案例参考(优化)

 

在NGINX中,可以通过配置文件和特定的指令来实现权限控制。以下是一些常见的权限控制方法:

  1. 使用deny指令:

    在NGINX配置文件中,可以使用deny指令来拒绝特定IP地址或IP地址范围的访问。可以将deny指令放在server块或location块中。

例如,要拒绝特定IP地址的访问,可以这样配置:

nginx复制代码
  server {
  ...
  deny 192.168.0.1; # 拒绝192.168.0.1的访问
  ...
  }

如果要拒绝一系列IP地址范围,可以这样配置:

nginx复制代码
  server {
  ...
  deny 192.168.0.0/24; # 拒绝192.168.0.0/24网段的访问
  ...
  }

 重启一下之后

 再次访问,就403没有权限了

 此时在06上还是可以的

 在location上添加拒绝,

 访问被拒绝只对这个location的资源生效

 其它服务器上,没有受到限制,对这个location下的资源

 

 

  1. 使用allow指令:

    deny指令相反,allow指令用于允许特定IP地址或IP地址范围的访问。可以将allow指令放在server块或location块中。

例如,要允许特定IP地址的访问,可以这样配置:

nginx复制代码
  server {
  ...
  allow 192.168.0.1; # 允许192.168.0.1的访问
  ...
  }

如果要允许一系列IP地址范围,可以这样配置:

nginx复制代码
  server {
  ...
  allow 192.168.0.0/24; # 允许192.168.0.0/24网段的访问
  ...
  }

 

拒绝网段所有,然后允许这个网段的某个IP。这样配置不行的,不会走到下面的允许,直接被拒绝了

 

 

 先允许这个IP,然后拒绝该IP其它网段的,这样才能生效

 

 

  1. 使用auth_basic指令:

    auth_basic指令用于对特定区域进行基本身份验证。可以将auth_basic指令放在location块中。需要与auth_basic_user_file指令一起使用来指定密码文件。

例如,要对特定目录进行基本身份验证,可以这样配置:

nginx复制代码
  location /private {
  auth_basic "Restricted Content";
  auth_basic_user_file /etc/nginx/.htpasswd; # 指定密码文件
  }

在上述示例中,访问以/private开头的URL将要求用户进行身份验证。可以使用工具(如htpasswd)生成密码文件。

 

如下,nginx上配置好

[root@mcw07 ~]$ vim /etc/nginx/nginx.conf
[root@mcw07 ~]$ echo '123456' >/etc/nginx/.htpasswd
[root@mcw07 ~]$ grep -C 4 htpasswd /etc/nginx/nginx.conf
        include /etc/nginx/default.d/*.conf;
       
        location /machangwei {
        auth_basic "Restricted Content";
        auth_basic_user_file /etc/nginx/.htpasswd;
        try_files $uri $uri/ /machangwei.html;  
        }

        error_page 404 /404.html;
[root@mcw07 ~]$ ls -lh /etc/nginx/.htpasswd
-rw-r--r-- 1 root root 7 Nov 15 21:17 /etc/nginx/.htpasswd
[root@mcw07 ~]$ nginx -t
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful
[root@mcw07 ~]$ nginx -s reload
[root@mcw07 ~]$ 

curl请求,访问报错401认证

 如果是网页访问的话,会这样,提示输入用户密码

 上面的密码文件配置有问题,应该按照如下的配置

 

在Nginx中,使用auth_basic指令可以启用基本的HTTP身份验证。通过指定一个密码文件,Nginx可以验证用户提供的凭据。

密码文件格式如下:

vbnet复制代码
  user1:$apr_md5$salt$encrypted_password
  user2:$apr_md5$salt$encrypted_password
  ...

每行包含一个用户名和其对应的加密密码。密码使用MD5哈希算法进行加密,并使用指定的盐值进行散列。在上面的示例中,user1user2是用户名,$apr_md5$salt$encrypted_password是对应的加密密码。

请注意,上述示例中的密码加密方式是使用Apache的apr_md5模块进行加密。这是Apache服务器默认使用的加密方式。如果你使用的是其他Web服务器或不同的加密方式,密码文件的格式可能会有所不同。

确保将密码文件放置在Nginx配置文件中指定的位置,并使用auth_basic指令将其与特定的目录关联起来。例如:

bash复制代码
  location /private {
  auth_basic "Restricted Content";
  auth_basic_user_file /etc/nginx/.pass;
  }

在上面的示例中,/etc/nginx/.pass是密码文件的路径。确保该文件具有适当的权限设置,以便Nginx可以读取和验证用户凭据。

 

nginx auth_basic的密码文件如何生成

要生成Nginx的auth_basic密码文件,您可以按照以下步骤进行操作:

  1. 确定密码文件的位置和名称。您可以将其放置在Nginx配置文件的任意位置,并为其选择一个合适的名称。例如,您可以将其命名为.passwd.password

  2. 打开终端或命令提示符,并导航到密码文件的位置。

  3. 使用htpasswd命令创建密码文件。如果您没有安装apache2-utils软件包,centos 安装yum install httpd-tools 这个包 请先安装它。在终端或命令提示符中运行以下命令:

bash复制代码
  sudo htpasswd -c /etc/nginx/.passwd username

/etc/nginx/.passwd替换为您选择的密码文件路径,并将username替换为您要创建密码的用户名。
4. 输入密码并确认。系统将要求您为所选用户名设置密码。

  1. 完成密码文件的创建后,您可以使用auth_basic指令将密码文件与特定的目录关联起来。在Nginx配置文件中,添加以下指令:

bash复制代码
  location /protected {
  auth_basic "Restricted Content";
  auth_basic_user_file /etc/nginx/.passwd;
  }

/etc/nginx/.passwd替换为您实际使用的密码文件路径。

添加用户密码之后

 

 页面成功访问

 如果想要curl访问添加了认证的nginx,那么需要指定用户密码

 

4. 使用satisfy指令:

 

在某些情况下,可能希望根据不同的请求方法进行不同的权限控制。可以使用satisfy指令来指定满足哪个条件时才进行身份验证。可以将satisfy指令放在location块中。

例如,要仅对POST请求进行身份验证,可以这样配置:

nginx复制代码
  location /login {
  satisfy post; # 只有POST请求需要身份验证
  auth_basic "Restricted Content";
  auth_basic_user_file /etc/nginx/.htpasswd; # 指定密码文件
  }

文心大模型3.5生成

 

 

NGINX中通过location将请求定位到本地静态文件

要在NGINX中将请求定位到本地静态文件,您可以使用location指令进行配置。以下是一个示例配置,将特定路径的请求映射到本地静态文件:

nginx复制代码
  server {
  listen 80;
  server_name example.com;
  root /var/www/example.com;
   
  location /images/ {
  # 将/var/www/example.com/images/目录下的文件映射到此路径
  root /path/to/local/images;
  try_files $uri $uri/ /index.html;
  }
   
  location / {
  # 其他路径的请求使用默认配置
  try_files $uri $uri/ /index.html;
  }
  }

在上面的配置中,location /images/指令将以/images/开头的所有请求映射到/path/to/local/images目录下的文件。这意味着如果您访问http://example.com/images/image.jpg,NGINX将尝试从/path/to/local/images/image.jpg提供该文件。

请注意,try_files指令用于处理文件不存在的情况。在此示例中,如果请求的文件不存在,NGINX将返回404 Not Found错误或指定的默认文件index.html

您可以根据您的实际需求调整路径和文件名。确保将路径设置为正确的本地文件路径,并使用正确的文件名和扩展名。

 

实战操作:

nginx上配置上

[root@mcw07 ~]$ echo "machangwei test" >/usr/share/nginx/html/machangwei.html
[root@mcw07 ~]$ grep -C 4 machangwei  /etc/nginx/nginx.conf
        deny 10.0.0.8;
        # Load configuration files for the default server block.
        include /etc/nginx/default.d/*.conf;
       
        location /machangwei {
        root     /usr/share/nginx/html;
        try_files $uri $uri/ /machangwei.html;  
        }

        error_page 404 /404.html;
        location = /404.html {
[root@mcw07 ~]$ nginx -t
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful
[root@mcw07 ~]$ nginx -s reload
[root@mcw07 ~]$ 

06上请求测试,正常请求到

 当把这个注释掉之后,也还是可以的,因为继承上面server标签下的了。

 

根据用户请求方式,直接从nginx这一层返回相应的状态 ,请求终止在nginx。

 

    location / {
        if ($request_method = POST){
          return 403;
        }
        if ($request_method = PUT){
          return 403;
        }
        if ($request_method = DELETE){
          return 403;
        }
        proxy_set_header Host xx.xx.com;
        proxy_pass http://xxx-nginx;
    }



upstream xxx-nginx {
    server ip  weight=10000 max_fails=3; 
}



xxx-nginx配置

location / {
        proxy_buffering off;
        proxy_set_header Host $http_host;
        proxy_pass http://hoiuduan;
    }

upstream houduan {
    server ip:9999 weight=10000;
    server ip:9999 weight=10000;
    server ip:9999 weight=10000;
    server ip:9999 weight=10000;
}

 

nginx流量镜像ngx_mirror_module

某次使用场景:一次请求,后面两个服务都能获取到请求体数据。其中一个镜像流量用于用户分析用

 

Nginx的流量镜像功能允许你将线上实时流量镜像到其他环境,如测试环境。这个过程可以用于故障分析、性能定位和迁移评估等功能。Nginx从1.13.4版本开始引入了ngx_mirror_module模块,通过该模块可以将请求复制一份,并根据mirror location中的配置来处理这份复制的请求。

当请求到达Nginx时,如果开启了流量镜像功能,Nginx会将请求复制一份,并根据mirror location中的配置来处理这份复制的请求。你可以通过指定请求将被镜像到的URI来控制镜像流量的目的地。默认情况下,复制的请求会被自动丢弃,这样就不会对原始客户端的请求造成影响。

需要注意的是,镜像请求和原始请求是相关联的,如果镜像请求没有处理完成,原始请求可能会被阻塞。因此,在测试环境中使用流量镜像时,要确保镜像后端能够及时处理请求,以避免对原始客户端的请求造成不必要的延迟或影响。

以上信息仅供参考,建议查阅Nginx官方文档或咨询相关技术人员以获取更准确和全面的信息。

 

 

要实现Nginx的流量镜像功能,你需要进行以下步骤:

  1. 确保你的Nginx版本支持ngx_mirror_module模块。你可以在Nginx的配置文件中添加http { ... }块,并在其中添加load_module /path/to/ngx_http_mirror_module.so;指令来加载该模块。

  2. 在Nginx的配置文件中添加mirror location块。在该块中,你可以指定镜像请求的URI和目标服务器。例如:

location /mirror {  
    internal;  
    proxy_pass http://mirror_backend;  
}
 

上述配置将请求复制到名为mirror_backend的后端服务器上。
3. 在需要镜像流量的原始请求中添加mirror指令。例如:

location / {  
    proxy_pass http://backend;  
    mirror /mirror;  
}

上述配置将原始请求转发到名为backend的后端服务器上,并将复制的请求发送到mirror_backend后端服务器上。
4. 重新加载或重启Nginx以使配置生效。

请注意,Nginx的流量镜像功能仅在开发环境和测试环境中使用。在生产环境中使用流量镜像可能会对性能和稳定性产生负面影响。因此,在使用流量镜像功能之前,请确保你了解其工作原理和潜在风险,并谨慎评估其适用性和必要性。

 

版本

# openresty -v
nginx version: openresty/1.19.3.1

 

openresty 配置

# vim /usr/local/openresty/nginx/conf/nginx.conf

    server {
        listen       8005;
        #listen       somename:8080;
        server_name  somename  alias  another.alias;

        location / {
            #root   /home/ares/mcw/mcwgitlab3;
          #  index  index.html index.htm;
            proxy_pass http://10.1x.xx.50:5000;
            mirror /mirror;
        }
       location /mirror {
      internal;
      proxy_pass http://10.1x.xx.50:5005;
 }
    }
}

5005服务的

# cat jiandan.py 
from flask import Flask,request, render_template  
app = Flask(__name__)  
#app.config['APPLICATION_ROOT'] = '/mirror'
  
@app.route('/mirror',methods=['GET', 'POST'])  
def home():
    print("=======>request.headers")
    print(request.headers)
    cc=str(request.headers)
    bb=''
    if request.method == 'POST':
        print('=======>request.form')
        print(request.form)
        bb= str(request.form)  
    return '%s,%s'%(cc,bb)
if __name__ == '__main__':
    app.run(host='0.0.0.0', port=5005)
# 

另外一个5000端口的,是下面这个网站

访问该网站

 当5005服务,路由没有带mirror的时候,会找不到,路由上带了,才能找到

 

 找不到的时候,也就是5005服务没有使用/mirror做路由的时候,匹配不到视图函数,5000服务会提示两个,一个成功,一个404,

 当5005服务,添加了mirror作为路由的时候,那么5000服务那里不会显示对5005服务的请求结果,并且5005服务上正常匹配到路由,打印出信息,包括get和post请求,都可以

client_max_body_size

client_max_body_size 500m; 

client_max_body_size 500m;

 

如下配置:

之前是上传500M ,上传2G以上的视频,报错413好像是这个错误。然后nginx改完5G,k8s ingress也改为5G就可以正常上传了。

这个域名对应的后端服务在k8s里,k8s应用是将上传的文件存入到阿里云oss中。

最大身体大小,应该是现在包的总的大小,而身体缓冲大小,只是写入缓冲,不需要跟最大身体大小一样大,个人理解。

 cat xx/xx/rewrite/fex-cloud
    location / {
        client_max_body_size 5G;
        client_body_buffer_size 500M;
        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_http_version 1.1;
        proxy_pass http://fex-cloud;
    }

 

ingress:
  metadata:
    annotations:
      kubernetes.io/ingress.class: nginx
      nginx.ingress.kubernetes.io/proxy-body-size: 5120m
      nginx.ingress.kubernetes.io/proxy-connect-timeout: '60'
      nginx.ingress.kubernetes.io/proxy-read-timeout: '60'
      nginx.ingress.kubernetes.io/proxy-send-timeout: '60'
      nginx.ingress.kubernetes.io/service-weight: ''
      nginx.ingress.kubernetes.io/enable-cors: "true"
  
  spec:
    rules:
      - host: 

 

m单位的案例,图片视频等上传的文件太大,被限制大小了

nginx转到k8s,nginx配置

    location / {
...........
        client_max_body_size 50m;
   .......
    }

k8s Ingress配置

ingress:
  metadata:
    annotations:
      kubernetes.io/ingress.class: nginx
      nginx.ingress.kubernetes.io/proxy-body-size: 50m
  spec:
    rules:
    - host: test-xx-rag-api.xx.com

 

流式输出proxy_buffering off;

添加proxy_buffering off;,支持流式输出。比如ai大模型中使用,如果没有的话,那么返回的文字是一块一块的渲染显示,如果配置了这个,那么就是一个一个的渲染显示,逐条显示,而不是多条一起显示。注意,如果a调用b,b调用chatgtp,那么这两个域名都要配置,因为这里遇到过,b没有配置,然后导致流式输出没有生效

    location / {
            proxy_pass ...
            ......
            proxy_buffering off;
    }

k8s ingress的添加

ingress:
  metadata:
    annotations:
      nginx.ingress.kubernetes.io/proxy-buffering: "off"
  spec:
    rules:
      - host: test-ai-xx-api.xx.com
      - host: test-ai-xx-api.xx.com

 

流式配置,比如域名解析到腾讯lb。lb转发到腾讯nginx云服务器,再到腾讯容器服务。这个路程中,配置nginx ,k8s ingress就可以了,lb不用做操作

 

 

基本的配置,可以看到客户端IP的

    location / {
            proxy_pass http://k8s-tx;
            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_http_version 1.1;
    }

前端放到minio参考配置

 

    rewrite  ^/statics/(.*).(svg|tif|tiff|wbmp|png|bmp|fax|gif|ico|jfif|jpe|jpeg|jpg|woff|cur|webp|swf|ttf|eot|woff2|css|js|txt|json|xhtml|html|map|exml|mp3|mp4|ogg|m4a)$ /frontend-old/oxxxsite/www.xx.com/statics/$1.$2 last;
    rewrite  ^/(en|pt|ru|in)$  /frontend-old/official-website/www.xx.com/$1/index.html last;
    rewrite  ^/(en|pt|ru|in)/$  /frontend-old/official-website/www.xx.com/$1/index.html last;
    rewrite  ^/(en|pt|ru|in)/(.*)/$ /frontend-old/official-website/www.xx.com/$1/$2.html last;
    rewrite  ^/(en|pt|ru|in)/(.*)  /frontend-old/official-website/www.xx.com/$1/$2.html last;

    set $host_mobile $host;

    if ($http_user_agent ~* "GoBrowser|MIDP|WAP|UP\.Browser|Obigo|Mobile|mobile|AU\.Browser|wxd\.Mms|WxdB\.Browser|CLDC|UP\.Link|KM\.Browser|UCWEB|SEMC-Browser|Mini|Symbian|Palm|Nokia|Panasonic|MOT-|SonyEricsson|NEC-|Alcatel|Ericsson|BENQ|BenQ|Amoisonic|Amoi|Capitel|PHILIPS|SAMSUNG|Lenovo|Mitsu|Motorola|SHARP|WAPPER|LG-|LG/|EG900|CECT|Compal|kejian|Bird|BIRD|G900/V1\.0|Arima|CTL|TDG|Daxian|DBTEL|Eastcom|EASTCOM|PANTECH|Dopod|Haier|HAIER|KONKA|KEJIAN|LENOVO|Soutec|SOUTEC|SAGEM|SEC|SED-|EMOL|INNO55|ZTE|Phone|phone|Android|WindowssCE|DX|TELSON|TCL|oppo|ChangHong|MALATA|TIANYU|MAUI|J2ME|BlackBerry|yulong|NOKIA|UNTRUSTED|SCH-|LGE-|CTC/1|kyocera|CEC-|DAXIAN|Sanyo-|Openwave|htc|Maemo|maemo|Mobi") {
      set $host_mobile m.xx.com;
    }

    location ^~ /frontend-old {
        if ($request_method = POST){
          return 403;
        }
        if ($request_method = PUT){
          return 403;
        }
        if ($request_method = DELETE){
          return 403;
        }
        proxy_set_header Host minio-xx.xxx.com;
        access_by_lua_block {
            ngx.ctx.upstream_name = "minio-xx-nginx"
        }
        proxy_pass http://backend;
        #proxy_pass http://minio-xx-nginx;
    }

    location = / {
        access_by_lua_block {
            ngx.ctx.upstream_name = "k8s-haproxy-xx"
        }
        proxy_pass http://backend_keepalive_64;
        #proxy_pass http://k8s-haproxy-xx;
        proxy_redirect    off;
        proxy_set_header Host www.xxx.com;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    }

    location / {
        access_by_lua_block {
            ngx.ctx.upstream_name = "k8s-haproxy-xx"
        }
        proxy_pass http://backend_keepalive_64;
        #proxy_pass http://k8s-haproxy-xx;
        proxy_redirect    off;
        proxy_set_header Host $host_mobile;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    }

 

nginx->haproxy->k8s的配置参考

➜  my-nginx git:(machangwei5) cat rewrite/qa-k8s
    location / {
        proxy_pass http://xx-k8s-ha2;

        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;
    }
➜  my-nginx git:(machangwei5)


➜  my-nginx git:(machangwei5) cat upstream/zz-idc/xx-k8s-ha2
upstream yf-k8s-ha2 {
    #server 10.10.16.31:8008 max_fails=3 weight=10000; # minio001.yf.mcw.cn
    #server 10.10.14.9:8008 max_fails=3 weight=10000; # vm-minio-proxy001.yf.mcw.cn
    server 10.11.14.29:8008 max_fails=3 weight=10000; # vm-minio-proxy001.zz.mcw.cn
}
➜  my-nginx git:(machangwei5)


# less /etc/haproxy/haproxy.cfg
listen test1  
bind 0.0.0.0:8008
mode tcp  
option tcpka
log         127.0.0.1 local2 info
balance roundrobin  

timeout client  600000  # 设置特定监听的客户端超时时间
timeout server  600000  # 设置特定监听的服务器超时时间

#server s1 10.0.8.37:80 weight 1 maxconn 10000 check inter 10s 
#server s2 10.0.8.38:80 weight 1 maxconn 10000 check inter 10s
#server s3 10.0.8.39:80 weight 1 maxconn 10000 check inter 10s
# server s2 10.0.15.221:30080 weight 1 maxconn 10000 check inter 10s
server s2 10.0.15.218:30080 weight 1 maxconn 10000 check inter 10s
# server s2 10.0.15.219:30080 weight 1 maxconn 10000 check inter 10s



# kubectl get svc --all-namespaces|grep  30080
ingress-nginx      ingress-nginx-controller             NodePort    10.xx.1xx.178   <none>        80:30080/TCP,443:30228/TCP      11d
[root@vm-qa-kubemaster001.zz.mcw.cn mcw]# 


[root@vm-qa-kubemaster001.zz.mcw.cn mcw]# kubectl get nodes -o wide
NAME                              STATUS   ROLES                  AGE   VERSION   INTERNAL-IP    EXTERNAL-IP   OS-IMAGE                KERNEL-VERSION                CONTAINER-RUNTIME
qa-x3.zz.mcw.cn            Ready    <none>                 11d   v1.28.0   10.0.15.219   <none>        CentOS Linux 7 (Core)   4.xpo.x86_64   docker://30.12.7
qa-kube004.zz.mcw.cn            Ready    <none>                 11d   v1.28.0   10.0.15.218   <none>        CentOS Linux 7 (Core)   5.x7.x86_64        docker://30.12.7
vm-qx002.zz.mcw.cn         Ready    <none>                 11d   v1.28.0   10.xx.20.3     <none>        CentOS Linux 7 (Core)   5xl7.x86_64         docker://30.12.7
vm-qaxter001.zz.mcw.cn   Ready    control-plane,master   11d   v1.28.0   10.xx.1xx4.7     <none>        CentOS Linux 7 (Core)   4.xel7.elrepo.x86_64   docker://30.12.7
[root@vm-qa-kubemaster001.zz.mcw.cn mcw]# 


综上: nginx->haproxy->k8s ingress 

80 rewrite调转443配置参考

server {
    listen 80;
    server_name sso.xxcn.com;

    rewrite      ^ https://$server_name$request_uri? permanent;


    access_log /data/logs/nginx/sso-xxcn_access.log main;
    error_log /data/logs/nginx/sso-xxscn_error.log;
}


server {
    listen 443 ssl;
    server_name sso.xxcn.com;

    location / {
        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_set_header X-Forwarded-Proto https;
        proxy_set_header X-Forwarded-Port 443;
        access_by_lua_block {
            ngx.ctx.upstream_name = "sso"
        }
        proxy_pass http://backend_keepalive_64;
        #proxy_pass http://sso;
        proxy_http_version 1.1;
        proxy_set_header Connection "";
    }


    ssl_certificate      ssl/xxcn.com.crt;
    ssl_certificate_key  ssl/xxcn.com.key;

    ssl_session_timeout  5m;

    ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
    ssl_ciphers  HIGH:!aNULL:!MD5;
    ssl_prefer_server_ciphers  on;
    access_log /data/logs/nginx/sso-xxcn_access.log main;
    error_log /data/logs/nginx/sso-xxcn_error.log;
}

 

配置文件参考nginx

# cat /usr/local/openresty/nginx/conf/nginx.conf
user  nobody nobody;

worker_processes auto;

error_log  /data/logs/nginx/nginx_error.log  notice;

pid    logs/nginx.pid;

#Specifies the value for maximuM FIle descriptors that can be opened by this process.
worker_rlimit_nofile 51200;

events {
    use epoll;
    worker_connections 51200;
    multi_accept on;
}

http {
    #realip module
    #include realip.conf;

    include       mime.types;
    default_type  application/octet-stream;

    server_names_hash_bucket_size 512;
    client_header_buffer_size 32k;
    large_client_header_buffers 4 32k;
    client_max_body_size 200m;
    client_body_buffer_size 1024k;

    sendfile on;
    tcp_nopush     on;

    keepalive_timeout 300;

    tcp_nodelay on;

    fastcgi_connect_timeout 300;
    fastcgi_send_timeout 300;
    fastcgi_read_timeout 300;
    fastcgi_buffer_size 64k;
    fastcgi_buffers 4 64k;
    fastcgi_busy_buffers_size 128k;
    fastcgi_temp_file_write_size 256k;

    gzip on;
    gzip_min_length  1k;
    gzip_buffers     4 16k;
    gzip_http_version 1.0;
    gzip_comp_level 2;
    gzip_types       text/plain application/x-javascript text/css text/xml application/xml application/atom+xml text/javascript application/json;
    gzip_vary on;
    gzip_proxied        expired no-cache no-store private auth;
    gzip_disable        "MSIE [1-6]\.";

    server_tokens off;
    #log format
    log_format main '$remote_addr - $remote_user [$time_local] "$request_method $uri $server_protocol" '
        '$status $request_length $body_bytes_sent $http_host "$http_referer" '
        '"$http_user_agent" "$http_x_forwarded_for" $request_time $upstream_response_time '
        '$upstream_addr $upstream_status $upstream_response_length $http_content_length';

    lua_shared_dict logdict 5m;
    log_by_lua_file luascripts/log.lua;

    include vhost/*.conf;
}

 

web socket支持配置

下面,可以实现的

 cat rewrite/zz-jumpserver-xx
    location / {
        proxy_pass http://zz-jumpserver-xxx;
        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_set_header Connection "";
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "upgrade";
    }

新增后四行

proxy_set_header Connection "";
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";

 

如果后端服务是在k8s里面,不需要给k8s配置。比如有个访问链路是到腾讯lb,域名转发到腾讯云实例nginx,然后到腾讯k8s,此时只是在腾讯云实例nginx上配置了下,就可以了。

 

超时连接问题,后端处理到返回数据给nginx需要时间太长,nginx超时时间限制返回网关超时

nginx到k8s服务,nginx配置

    location / {
...........
        proxy_read_timeout 600s;
        proxy_connect_timeout  600s;
        proxy_send_timeout 600s;
.......
    }

k8s ingress 配置

ingress:
  metadata:
    annotations:
      kubernetes.io/ingress.class: nginx
      nginx.ingress.kubernetes.io/proxy-read-timeout: '600'
      nginx.ingress.kubernetes.io/proxy-connect-timeout:  '600'
      nginx.ingress.kubernetes.io/proxy-send-timeout: '600'     
  spec:
    rules:
    - host: test-agent-rag-api.xx.com

 

指定路径返回字符串或者响应码或者响应页面

 

    location = / {
    return 200 "ok";
  }
    location / {
        if ($request_method = POST){
          return 403;
        }
        if ($request_method = PUT){
          return 403;
        }
        if ($request_method = DELETE){
          return 403;
        }
    location @errors {
        return 403 "=== Permission Diney 403! ===\r\n";
    }

 

nginx到minio前端存储部分参考

如果只有它 rewrite ^/(.*) /actxx/$1 break;  那么需要拼接文件路径进行访问,有前端路由的就容易出现问题

如果只有下面两个,那么前端vue,有前端路由啥的,静态文件会在地址栏的基础上拼接,这样 静态文件的地址就多了前端路由了

        rewrite  ^/(.*).(svg|tif|tiff|wbmp|png|bmp|fax|gif|ico|jfif|jpe|jpeg|jpg|woff|cur|webp|swf|ttf|eot|woff2|css|js|txt|json|xhtml|html|mp4|map|rplib)$ /actxx/ci/allcc-customer/$1.$2 last;
        rewrite  ^/(.*) /actxx/ci/allcc-customer/index.html last;

如果是下面三个都加上。其它方面不变,只有访问静态文件的时候,直接从项目根目录开始,就不会拼接路由,给静态目录assets单独做匹配,然后直接从根目录下的assets开始。这个才是符合预期效果

        rewrite  ^/(.*)/assets/(.*).(svg|tif|tiff|wbmp|png|bmp|fax|gif|ico|jfif|jpe|jpeg|jpg|woff|cur|webp|swf|ttf|eot|woff2|css|js|txt|json|xhtml|html|mp4|map|rplib)$ /actxx/ci/allcc-customer/assets/$2.$3 last;
        rewrite  ^/(.*).(svg|tif|tiff|wbmp|png|bmp|fax|gif|ico|jfif|jpe|jpeg|jpg|woff|cur|webp|swf|ttf|eot|woff2|css|js|txt|json|xhtml|html|mp4|map|rplib)$ /actxx/ci/allcc-customer/$1.$2 last;
        rewrite  ^/(.*) /actxx/ci/allcc-customer/index.html last;

 

    location = / {
    return 200 "ok";

  }

        rewrite  ^/(.*)/assets/(.*).(svg|tif|tiff|wbmp|png|bmp|fax|gif|ico|jfif|jpe|jpeg|jpg|woff|cur|webp|swf|ttf|eot|woff2|css|js|txt|json|xhtml|html|mp4|map|rplib)$ /actxx/ci/allcc-customer/assets/$2.$3 last;
        rewrite  ^/(.*).(svg|tif|tiff|wbmp|png|bmp|fax|gif|ico|jfif|jpe|jpeg|jpg|woff|cur|webp|swf|ttf|eot|woff2|css|js|txt|json|xhtml|html|mp4|map|rplib)$ /actxx/ci/allcc-customer/$1.$2 last;
        rewrite  ^/(.*) /actxx/ci/allcc-customer/index.html last;

    location / {
        if ($request_method = POST){
          return 403;
        }
        if ($request_method = PUT){
          return 403;
        }
        if ($request_method = DELETE){
          return 403;
        }
        add_header Access-Control-Allow-Origin *;
        #rewrite ^/$    /actxx/index.html break;
        #rewrite ^/(.*) /actxx/$1 break;
        proxy_set_header Host minio.xx.com;
        access_by_lua_block {
            ngx.ctx.upstream_name = "minio-xx-nginx"
        }
        proxy_pass http://backend;
        #proxy_pass http://minio-xx-nginx;
    }

 

posted @ 2023-11-15 18:03  马昌伟  阅读(337)  评论(0编辑  收藏  举报
博主链接地址:https://www.cnblogs.com/machangwei-8/