2022-08-22-nginx配置

1. root

语法:root path 配置段:http、server、location、if

root的处理结果是:root路径+location路径

location /t/ {
     root /www/root/html/;
}

请求的URI是/t/a.html时,web服务器将会返回服务器上的/www/root/html/t/a.html的文件。

2.alias

语法:alias path 配置段:location

alias的处理结果是:使用alias路径替换location路径 alias后面必须要用“/”结束,否则会找不到文件的。。。而root则可有可无

location /t/ {
 alias /www/root/html/new_t/;
}

请求的URI是/t/a.html时,web服务器将会返回服务器上的/www/root/html/new_t/a.html的文件。

3.try_files

语法:try_files 文件路径… 重写的uri 配置段:server location

try_files后面至少要有一个文件路径一个重写uri。 查找路径是按照给定的root或alias为根路径来查找的; 如果给出的file都没有匹配到,则会进行一个内部重定向到最后一个参数给定的uri,就是新的location匹配; 最后一个参数是回退URI且必须存在,否则会出现内部500错误;

location / {
  root /data/dist;
  try_files $uri $uri/ /index.html
  expires 7d; # expires 是nginx控制缓存的一种方式,7d=7天。
}

访问http://localhost/example?a=1时$uri为/example,$request_uri包括URI参数为/example?a=1,处理顺序是:

$uri是指/example文件, 会先找root目录/data/dist下的/example文件,也就是/data/dist/example这个文件,找到直接返回。 $uri/也就是/example/目录,找不到再尝试找/data/dist/example/目录下的index开头的文件,找到直接返回。 如果前面文件都没匹配找到,就会 fallback 到 try_files 的最后一个选项 /index.html,发起一个内部 “子请求”,也就是相当于 nginx 发起一个 HTTP 请求到 http://localhost/index.html。重新匹配location。

location / {
  try_files /app/cache/ $uri @fallback;
  index index.php index.html;
}

location @fallback {
  rewrite ^/(.*)$ http://www.baidu.com # 跳转到百度,和try_files最后一个参数作用相同。
}

sub_filter 过滤及替换响应内容

Accept-Encoding 设为空值,以禁用压缩,是因为 sub_filter 只能处理未经压缩的内容;又 sub_filter 一般只替换 text/html 且仅工作一次,不符合需求,故对配置稍做微调。

location / {
    ... 
    proxy_set_header Accept-Encoding '';
    sub_filter_types *;
    sub_filter_once off;
    sub_filter '查找内容:源站域名' '替换为:反代站域名';
    ...
}

rewrite 和 location

表面看 rewrite 和 location 功能有点像,都能实现跳转,主要区别在于 rewrite 是在同一域名内更改获取资源的路径,而 location 是对一类路径做控制访问或反向代理,可以 proxy_pass 到其他机器。很多情况下 rewrite 也会写在 location 里,它们的执行顺序是:

执行 server 块的 rewrite 指令(这里的块指的是 server 关键字后{}包围的区域,其它 xx 块类似) 执行location匹配 执行选定的location中的rewrite指令 如果其中某步 URI 被重写,则重新循环执行1-3,直到找到真实存在的文件; 如果循环超过 10 次,则返回 500 Internal Server Error 错误。

匹配不到的话,重定向到 @fallback,然后重写到百度。

location 优先级介绍

location 匹配方式有以下几种

  1. location = /path/a/exact.png {}: 精确匹配
  2. location ^~ /path/a/ {}: 优先前缀匹配(符合最长匹配原则)
  3. location ~ /Path?/ {} : 区分大小写正则匹配(首次匹配原则)
  4. location ~* /path?/ {} : 不区分大小写正则匹配(首次匹配原则)
  5. location /path/a/test.png {} : 前缀匹配(符合最长匹配原则)
  6. location 优先级匹配与配置的先后顺序无关,优先级排列顺序如下

精确匹配 > 优先前缀匹配 > 区分大小写正则匹配=不区分大小写正则匹配 > 前缀匹配

rewrite 指令

语法:rewrite regex replacement [flag]; 作用域:server 、location、if 功能:如果一个URI匹配指定的正则表达式regex,URI就按照 replacement 重写。

rewrite 按配置文件中出现的顺序执行。可以使用 flag 标志来终止指令的进一步处理。

如果 replacement 以 http:// 、 https:// 或 $ scheme 开始,将不再继续处理,这个重定向将返回给客户端。 示例:第一种情况,重写的字符串带 http://

location ^~ /redirect {
    # 当匹配前缀表达式 /redirect/(.*)时 请求将被临时重定向到 http://www.$1.com
    # 相当于 flag 写为 redirect
    rewrite ^/(.*)$ http://www.$1.com;
    return 200 "ok";
}

在浏览器中输入 127.0.0.1:8080/redirect/baidu ,则临时重定向到 www.baidu.com 后面的 return 指令将没有机会执行了。

location ^~ /redirect {
    rewrite ^/(.*)$ www.$1.com;
    return 200 "ok";
}

发送请求如下

curl 127.0.0.1:8080/redirect/baidu

ok

此处没有带 http:// 所以只是简单的重写。请求的 URI 由 /test1/baidu 重写为 www.baidu.com 因为会顺序执行 rewrite 指令,所以 下一步执行 return 指令,响应后返回 ok

flag 有四种参数可以选择:

last 停止处理后续 rewrite 指令集,然后对当前重写的新 URI 在 rewrite 指令集上重新查找。 break 停止处理后续 rewrite 指令集,并不再重新查找,但是当前location 内剩余非 rewrite 语句和 location 外的 非rewrite 语句可以执行。 redirect 如果 replacement 不是以 http:// 或 https:// 开始,返回 302 临时重定向 permanent 返回 301 永久重定向 示例 1:

rewrite 后面没有任何 flag 时就顺序执行

当 location 中没有 rewrite 模块指令可被执行时 就重写发起新一轮location 匹配

location / {
    # 顺序执行如下两条rewrite指令 
    rewrite ^/test1 /test2;
    rewrite ^/test2 /test3;  # 此处发起新一轮 location 匹配 URI为/test3
}

location = /test2 {
    return 200 “/test2”;
}  

location = /test3 {
    return 200 “/test3”;
}

发送如下请求

curl 127.0.0.1:8080/test1

/test3

如果正则表达regex式中包含 “}” 或 “;”,那么整个表达式需要用双引号或单引号包围。

示例 2:

location / {
    rewrite ^/test1 /test2;
    rewrite ^/test2 /test3 last;  # 此处发起新一轮location匹配 uri为/test3
    rewrite ^/test3 /test4;
    proxy_pass http://www.baidu.com;
}

location = /test2 {
    return 200 "/test2";
}  

location = /test3 {
    return 200 "/test3";
}
location = /test4 {
    return 200 "/test4";
}

发送如下请求 curl 127.0.0.1:8080/test1 返回 /test3

当如果将上面的 location / 改成如下代码

location / {
    rewrite ^/test1 /test2;
    # 此处不会发起新一轮location匹配;当是会终止执行后续rewrite模块指令重写后的 URI 为 /more/index.html
    rewrite ^/test2 /more/index.html break;  
    rewrite /more/index\.html /test4; # 这条指令会被忽略

    # 因为 proxy_pass 不是rewrite模块的指令 所以它不会被 break终止
    proxy_pass https://www.baidu.com;
}

发送请求 127.0.0.1:8080/test1 代理到 https://www.baidu.com

rewrite 后的请求参数: 如果替换字符串 replacement 包含新的请求参数,则在它们之后附加先前的请求参数。如果你不想要之前的参数,则在替换字符串 replacement 的末尾放置一个问号,避免附加它们。

由于最后加了个 ?,原来的请求参数将不会被追加到 rewrite 之后的 URI 后面*

rewrite ^/users/(.*)$ /show?user=$1? last;

正则表达式

  • 1、= 开头
  • 精确匹配
    location = /login { ... }
    
  • 2、^~ 开头
  • 表示 URL 以某个常规字符串开头,不区分大小写,并关闭正则匹配,当搜索到这个普通匹配模式后,将不再继续搜索正则匹配模式。
    location ^~ /static/ { ... }
    
  • 3、~ 开头
  • 表示区分大小写的正则匹配,以gif、jpg、js、css结尾
    location ~ \.(gif|jpg|png|js|css)$ { ... }
    
  • 4、~* 开头
  • 表示不区分大小写的正则匹配,以 .png 结尾
    location ~* \.png$ { ... }
    
  • 5、/ 开头
  • 通用匹配,任何请求都会匹配到。
    location / { ... }
    
  • 各符号优先级:
  • = > ^~ > ~ ~* > /
  • .表示除\n之外的任意字符
  • *表示匹配0-无穷
  • +表示匹配1-无穷

墙代理+nginx图片服务

server {
    listen 80;
    listen [::]:80;
    server_name blowsysun.top;
    return 301 https://$server_name:443$request_uri;
}

server {
    listen       443 ssl http2;
    listen       [::]:443 ssl http2;
    server_name blowsysun.top;
    charset utf-8;

    # ssl配置
    ssl_ciphers ECDHE-RSA-AES128-GCM-SHA256:ECDHE:ECDH:AES:HIGH:!NULL:!aNULL:!MD5:!ADH:!RC4;
    ssl_ecdh_curve secp384r1;
    ssl_prefer_server_ciphers on;
    ssl_session_cache shared:SSL:10m;
    ssl_session_timeout 10m;
    ssl_session_tickets off;
    ssl_certificate /etc/v2ray/blowsysun.top.pem;
    ssl_certificate_key /etc/v2ray/blowsysun.top.key;

    # root /usr/share/nginx/html;
    location / {
        root /usr/share/nginx/html;
        proxy_ssl_server_name on;
        proxy_pass https://86817.com/;
        proxy_set_header Accept-Encoding '';
        sub_filter "86817.com" "blowsysun.top";
        sub_filter_once off;
    }

    location = /robots.txt {}

    location /images/ {
      root /usr/share/nginx/;
      autoindex on; # 打开目录浏览功能
      #autoindex_exact_size off; #默认为on,显示出文件的确切大小,单位是bytes。改为off后,显示出文件的大概大小,单位是kB或者MB或者GB
      #autoindex_localtime on; #默认为off,显示的文件时间为GMT时间。
改为on后,显示的文件时间为文件的服务器时间
      #charset utf-8;
    }

    location /nEmeUFJM0hbD {
      proxy_redirect off;
      proxy_pass http://127.0.0.1:22768;
      proxy_http_version 1.1;
      proxy_set_header Upgrade $http_upgrade;
      proxy_set_header Connection "upgrade";
      proxy_set_header Host $host;
      # Show real IP in v2ray access.log
      proxy_set_header X-Real-IP $remote_addr;
      proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    }
}

项目1

worker_processes auto;
worker_rlimit_nofile 65535;
error_log logs/error.log;
pid /var/run/nginx.pid;
daemon off;

events {
    worker_connections 2048;
}

http {
    log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                      '$status $body_bytes_sent "$http_referer" '
                      '"$http_user_agent" "$http_x_forwarded_for" "$http_referer"';

    access_log  logs/access.log  main;
    client_max_body_size    100m;
    sendfile            on;
    tcp_nopush          on;
    tcp_nodelay         on;
    keepalive_timeout   65;
    types_hash_max_size 2048;

    gzip on;
    gzip_disable "msie6";
    gzip_vary on;
    gzip_proxied any;
    gzip_comp_level 6;
    gzip_buffers 16 8k;
    gzip_http_version 1.1;
    gzip_min_length 256;
    gzip_types text/plain text/css application/json application/x-javascript text/xml application/xml application/xml+rss application/javascript text/javascript application/vnd.ms-fontobject application/x-font-ttf font/opentype image/svg+xml image/x-icon;

    proxy_connect_timeout 300s;
    proxy_send_timeout 300s;
    proxy_read_timeout 300s;
    send_timeout 300s;
    fastcgi_connect_timeout 300;
    fastcgi_send_timeout 300;
    fastcgi_read_timeout 300;

    include             /usr/local/openresty/nginx/mime.types;
    default_type        application/octet-stream;

    # Load modular configuration files from the /etc/nginx/conf.d directory.
    # See http://nginx.org/en/docs/ngx_core_module.html#include
    # for more information.
    include servers/*.conf;

    server {
        listen       80 default_server;
	    	listen       [::]:80 default_server;
        server_name  _;
        #root         /usr/local/openresty/nginx/html/;

        # 重写env.config.js路径
        location ~ .+/env.config.js$  {
           rewrite ^(.*)$ /env.config.js break;
           root  /usr/local/openresty/nginx/html;
        }

        # 重写/static_res资源路径
        location ~ .+/static_res/  {
           rewrite ^.*(\/static_res\/.*)$ $1 break;
           root  /usr/local/openresty/nginx/html;
        }

        # 重写/assets/img/中图片资源路径
        location ~ .+/assets_res/  {
           rewrite ^.*(\/assets_res\/.*)$ $1 break;
           root  /usr/local/openresty/nginx/html;
        }

        # 重写/assets/img/中图片资源路径
        location ~ .+/assets/  {
           rewrite ^.*(\/assets\/.*)$ $1 break;
           root  /usr/local/openresty/nginx/html;
        }

        # 主入口配置
        location / {
            add_header Cache-Control 'no-cache, must-revalidate, proxy-revalidate, max-age=0';
            alias /usr/local/openresty/nginx/html/;
            index index.html;
            try_files $uri $uri/ /index.html;

            if ($request_filename ~* .*.(html|htm)$)
            {
                expires -1s;
            }

            if ($request_filename ~* .*.(gif|jpg|jpeg|png|svg)$)
            {
                expires 30d;
            }

            if ($request_filename ~ .*.(js|css)$)
            {
                expires 12h;
            }
        }

        # 接口
        location /xadmin/ {
            proxy_pass http://xxx-backend:8090;
            rewrite ^/xadmin/(.*)$ /xadmin/$1 break;
        }
        location /platform/ {
            proxy_pass http://xxx-backend:8080;
            rewrite ^/platform/(.*)$ /platform/$1 break;
        }
        
        location /ping {
            return 200 "oK";
        }

        error_page 404 /404.html;
            location = /40x.html {
        }

        error_page 500 502 503 504 /50x.html;
            location = /50x.html {
        }
    }
}

项目2 - 微前端 独立部署

user  root;
worker_processes  auto;

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

#pid        logs/nginx.pid;


events {
    worker_connections  1024;
}


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;
    tcp_nodelay         on;
    keepalive_timeout   65;
    types_hash_max_size 2048;

    server {
        listen       80 default_server;
        listen       [::]:80 default_server;
        server_name  _;
        root         /usr/share/nginx/html;

        # 资源下载
        location ^~ /zyx/portal/doc/ {
           #需要下载的文件存放的目录
           alias  /data/zyx_web/;
           sendfile on;
           autoindex on;  # 开启目录文件列表
           autoindex_exact_size on;  # 显示出文件的确切大小,单位是bytes
           autoindex_localtime on;  # 显示的文件时间为文件的服务器时间
           charset utf-8,gbk;  # 避免中文乱码
       }

        # 主应用
        location ^~/zyx {
              alias /data/zyx_web/zyx-web-main;
              index index.html;
              try_files $uri $uri/ /zyx/index.html;
        }

        # 政企通
        location ^~/zyx/sub/enterprise {
              add_header Cache-Control 'no-cache, must-revalidate, proxy-revalidate, max-age=0';
              alias /data/zyx_web/zyx-web-government-enterprise-through;
              index index.html;
              try_files $uri $uri/ /zyx/sub/enterprise/index.html;
        }

        # 统一门户
        location ^~/zyx/sub/portal {
              add_header Cache-Control 'no-cache, must-revalidate, proxy-revalidate, max-age=0';
              alias /data/zyx_web/zyx-web-portal;
              index index.html;
              try_files $uri $uri/ /zyx/sub/portal/index.html;
        }
        # 标签系统
        location ^~/zyx/sub/tag {
                add_header Cache-Control 'no-cache, must-revalidate, proxy-revalidate, max-age=0';
                alias /data/zyx_web/zyx-web-tag;
                index index.html;
                try_files $uri $uri/ /zyx/sub/tag/index.html;
        }
    }
}

项目3 - 微前端 合并部署

user  root;
worker_processes auto;
worker_rlimit_nofile 65535;
error_log logs/error.log;
pid /var/run/nginx.pid;
daemon off;

events {
    worker_connections 2048;
}

http {
    log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                      '$status $body_bytes_sent "$http_referer" '
                      '"$http_user_agent" "$http_x_forwarded_for" "$http_referer"';

    access_log  logs/access.log  main;
    client_max_body_size    100m;
    sendfile            on;
    tcp_nopush          on;
    tcp_nodelay         on;
    keepalive_timeout   65;
    types_hash_max_size 2048;
    
    gzip on;
    gzip_static on;
    gzip_disable "msie6";
    gzip_vary on;
    gzip_proxied any;
    gzip_comp_level 6;
    gzip_buffers 16 8k;
    gzip_http_version 1.0;
    gzip_min_length 20;
    gzip_types text/plain text/css application/json application/x-javascript text/xml application/xml application/xml+rss application/javascript text/javascript application/vnd.ms-fontobject application/x-font-ttf font/opentype image/svg+xml image/x-icon;


    proxy_connect_timeout 300s;
    proxy_send_timeout 300s;   
    proxy_read_timeout 300s;   
    send_timeout 300s;    
    fastcgi_connect_timeout 300;    
    fastcgi_send_timeout 300;   
    fastcgi_read_timeout 300;     

    include             /usr/local/openresty/nginx/mime.types;
    default_type        application/octet-stream;

    include servers/*.conf;
  
    server {
        listen       80 default_server;
        listen       [::]:80 default_server;
        server_name  _;
        # 重写env.config.js路径
        location ~ .+/env.config.js$  {
           rewrite ^(.*)$ /env.config.js break;
           root  /usr/local/openresty/nginx/html;
        }
        
        location ^~ /zyx_dev {
            add_header Cache-Control 'no-cache, must-revalidate, proxy-revalidate, max-age=0';
            proxy_hide_header Host;
            alias /usr/local/openresty/nginx/html/zyx-web-main;
            index index.html;
            try_files $uri $uri/ /index.html;

            if ($request_filename ~* .*.(html|htm)$)
            {
                expires -1s;
            }

            if ($request_filename ~* .*.(gif|jpg|jpeg|png|svg)$)
            {
                expires 30d;
            }

            if ($request_filename ~ .*.(js|css)$)
            {       
                expires 12h;
            }
        }
        location /zyx_dev/sub/portal {
            add_header Cache-Control 'no-cache, must-revalidate, proxy-revalidate, max-age=0';
            alias /usr/local/openresty/nginx/html/zyx-web-portal;
            index index.html;
            try_files $uri $uri/ /zyx/sub/portal/index.html;
        }
        location /zyx_dev/sub/enterprise {
            add_header Cache-Control 'no-cache, must-revalidate, proxy-revalidate, max-age=0';
            alias /usr/local/openresty/nginx/html/zyx-web-government-enterprise-through;
            index index.html;
            try_files $uri $uri/ /zyx/sub/enterprise/index.html;
        }
        location /zyx_dev/sub/tag {
            add_header Cache-Control 'no-cache, must-revalidate, proxy-revalidate, max-age=0';
            alias /usr/local/openresty/nginx/html/zyx-web-tag;
            index index.html;
            try_files $uri $uri/ /zyx/sub/tag/index.html;
        }
        error_page 404 /404.html;
            location = /40x.html {
        }

        error_page 500 502 503 504 /50x.html;
            location = /50x.html {
        } 
    }
}