fangmd / blogsource

6 stars 0 forks source link

Nginx #15

Open fangmd opened 3 years ago

fangmd commented 3 years ago

作用:

  1. 静态文件服务器
  2. 反向代理(缓存加速,负载均衡)

优点:

  1. 负载均衡:方便横向扩充
  2. 反向代理:隐藏真实服务器
  3. 动静分离
fangmd commented 3 years ago

Nginx 配置文件位置

Linux: /etc/nginx

基本使用命令

  1. 通过信号量操作 nginx
nginx -s [send signal to a master process: stop, quit, reopen, reload]
fangmd commented 3 years ago

配置文档: https://nginx.org/en/docs/

Nginx 配置文件结构

  1. main: 全局设置
  2. events: 事件模块设置
  3. http(server>location): HTTP 核心模块设置
  4. server:
user nginx;
//...
events {
  //...
}
http {
  // ...
  server {
    location path {
      // ...
    }
  server {
    location path {
      // ...
     }
  }
}

main config

  1. 工作进程数量
Syntax:  worker_processes number | auto;
Default: worker_processes 1;
Context: main

events config

  1. worker 子进程能处理的最大并发连接数
Syntax: worker_connections number;
Default: worker_connections 512;
Context: events

server config

  1. listen: 监听端口
listen 80;
  1. server_name
server_name example.com www.example.com;
server_name example.com *.example.com www.example.*;
server_name ~^(www\.)?(.+)$;
  1. root, alias 异同

使用环境不一样

root Context: http, server, location, if
alias Context: location

路径拼接方式不一样:

root: 叠加 path
alias: 不叠加 path
  1. location

优先级:= > ^~ > ~ > ~* > 不带任何字符

结尾 / 含义: 表示作为目录处理,如果不带作为目录或者文件处理。

  1. stub_status: 显示 Nginx 某个 location 状态

状态:接受的客户端连接总数量,处理的客户端数量,活跃的连接数量。。。

Context: location
fangmd commented 3 years ago

upstream 定义上游服务器

Syntax: upstream name { ... }
Default:    —
Context:    http
  1. server
Syntax:  server address [parameters]; (weight=number, max_conns=number, max_fails=number, fail_timeout=time, backup, down,)
Default: --
Context upstream
fangmd commented 3 years ago

Nginx 安装 & 卸载

CentOS

$ sudo yum -y install nginx   # 安装 nginx
$ sudo yum remove nginx  # 卸载 nginx

位置:/etc/nginx

配置 Nginx 服务:

$ sudo systemctl enable nginx # 设置开机启动 
$ sudo service nginx start # 启动 nginx 服务
$ sudo service nginx stop # 停止 nginx 服务
$ sudo service nginx restart # 重启 nginx 服务
$ sudo service nginx reload # 重新加载配置,一般是在修改过 nginx 配置文件时使用。

Ubuntu

sudo apt update
sudo apt install nginx
fangmd commented 3 years ago

gzip 配置:

# /etc/nginx/conf.d/gzip.conf
gzip on; # 默认off,是否开启gzip
gzip_types text/plain text/css application/json application/x-javascript text/xml application/xml application/xml+rss text/javascript;
# 上面两个开启基本就能跑起了,下面的愿意折腾就了解一下
gzip_static on;
gzip_proxied any;
gzip_vary on;
gzip_comp_level 6;
gzip_buffers 16 8k;
# gzip_min_length 1k;
gzip_http_version 1.1;

以下来自:https://www.nginxedit.cn/

# /etc/nginx/conf.d/gzip.conf
# gzip
gzip on;
gzip_vary on;
gzip_proxied any;
gzip_comp_level 6;
gzip_types text/plain text/css text/xml application/json application/javascript application/rss+xml application/atom+xml image/svg+xml;
fangmd commented 3 years ago

Nginx 高可用集群

keepalived

fangmd commented 3 years ago

静态服务

server {
  listen       80;
  server_name  static.sherlocked93.club;
  charset utf-8;    # 防止中文文件名乱码

  location /download {
    alias             /usr/share/nginx/html/static;  # 静态资源目录

    autoindex               on;    # 开启静态资源列目录
    autoindex_exact_size    off;   # on(默认)显示文件的确切大小,单位是byte;off显示文件大概大小,单位KB、MB、GB
    autoindex_localtime     off;   # off(默认)时显示的文件时间为GMT时间;on显示的文件时间为服务器时间
  }
}
fangmd commented 3 years ago

SPA web 服务器

server {
  listen       80;
  server_name  fe.sherlocked93.club;

  location / {
    root       /usr/share/nginx/html/dist;  # vue 打包后的文件夹
    index      index.html index.htm;
    try_files  $uri $uri/ /index.html @rewrites;  

    expires -1;                          # 首页一般没有强制缓存
    add_header Cache-Control no-cache;
  }

  # 接口转发,如果需要的话
  #location ~ ^/api {
  #  proxy_pass http://be.sherlocked93.club;
  #}

  location @rewrites {
    rewrite ^(.+)$ /index.html break;
  }
}

index.html 不做缓存: (协商缓存在移动端比如微信下会失效,所以 html 不做缓存)

    # index.html 不做缓存
    add_header Last-Modified $date_gmt;
    add_header Cache-Control 'no-store, no-cache, must-revalidate, proxy-revalidate, max-age=0';
    if_modified_since off;
    expires off;
    etag off;
fangmd commented 3 years ago

Http 转发到 Https

server {
    listen      80;
    server_name www.sherlocked93.club;
    # 单域名重定向
    if ($host = 'www.sherlocked93.club'){
        return 301 https://www.sherlocked93.club$request_uri;
    }
    # 全局非 https 协议时重定向
    if ($scheme != 'https') {
        return 301 https://$server_name$request_uri;
    }
    # 或者全部重定向
    return 301 https://$server_name$request_uri;
    # 以上配置选择自己需要的即可,不用全部加
}
fangmd commented 3 years ago

SPA Web 2

{
    #listen 443;
    listen       80;
    listen       443 ssl;
    server_name merchantcoin.io;
    #ssl on;
    ssl_certificate /etc/nginx/ssl/cubicpay.io.crt;
    ssl_certificate_key /etc/nginx/ssl/key.pem;
    index index.html;
    root /data0/app/merchantcoin/;
    location ~ .*\.(gif|jpg|jpeg|png|bmp|swf)$
    {
        expires 30d;
    }
    location ~ .*\.(js|css)?$
    {
        expires 1h;
    }

    location / {
        if ($request_method = 'OPTIONS') {
            add_header 'Access-Control-Allow-Headers' *;
            add_header Access-Control-Allow-Origin *;
            add_header Access-Control-Allow-Methods GET,POST,PUT,DELETE,PATCH,OPTIONS;
             return 200;
        }
        root /data0/app/merchantcoin/;
        index  index.html index.htm;
        if (!-e $request_filename) {
            rewrite ^/(.*) /index.html last;
            break;
        }
    }
}
fangmd commented 2 years ago

ip nginx 透传

服务端获取客户端ip时使用

    location /api {
        proxy_set_header Host $http_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 $scheme;

        # rewrite ^/api/(.*)$ /$1 break;
        proxy_pass http://127.0.0.1:9001;
    }
fangmd commented 2 years ago

websocket 配置

        location /socket.io {
            # rewrite ^/api/(.*)$ /$1 break;
            proxy_pass http://host.docker.internal:9031;
            proxy_http_version 1.1;
            proxy_set_header Upgrade $http_upgrade;
            proxy_set_header Connection "upgrade";
        }
fangmd commented 2 years ago

图片防止盗链

server {
  listen       80;        
  server_name  *.sherlocked93.club;

  # 图片防盗链
  location ~* \.(gif|jpg|jpeg|png|bmp|swf)$ {
    valid_referers none blocked server_names ~\.google\. ~\.baidu\. *.qq.com;  # 只允许本机 IP 外链引用,感谢 @木法传 的提醒,将百度和谷歌也加入白名单
    if ($invalid_referer){
      return 403;
    }
  }
}
fangmd commented 1 year ago

文件大小限制

server {
    listen 3022;
    server_name 103.38.227.62;

   client_max_body_size 1024M;
   client_header_timeout    30m;
   client_body_timeout      30m;
   proxy_connect_timeout     60s;
   proxy_read_timeout      30m;
   proxy_send_timeout      30m;

 ...
}

文件下载大小限制

proxy_max_temp_file_size 3072M
fangmd commented 1 year ago

部署多个前端项目

  1. 前端路由添加前缀: <BrowserRouter basename='app1'>
  2. 前端打包增加 publicPath : publicPath: '/app1/',
  3. nginx 配置
server {
  listen       9003;
  server_name  0.0.0.0 localhost;

  root /web/spa/build;

  location /app1 {
    index      index.html index.htm;
    try_files  $uri $uri/ /app1/index.html;
  }

  location /app2 {
    index      index.html index.htm;
    try_files  $uri $uri/ /app2/index.html;
  }

}
fangmd commented 11 months ago

nginx 自动跳转带上了 port 的问题

问题:访问 http://localhost:9080/dist 会自动跳转到 http://localhost:9080/dist/ 同时会带上 nginx 配置的端口,如果 nginx 在 docker 中,并且 docker 端口和 nginx 端口不一致的时候就会出问题

port_in_redirect off ; 解决自动跳转带上 port 的问题

server {
     listen       8000;
     server_name  localhost;
     port_in_redirect off ;
    location /hyyy {
        root   /app/hyyy; #虚机用户目录
        index  index.html index.htm;
        try_files $uri $uri/ /hyyy/index.html;
    }
...
}

取消跳转

absolute_redirect off;
fangmd commented 7 months ago

nginx server_name 不匹配也能访问的问题

nginx 在处理请求的时候,如果没有能匹配的 server,就会让同端口的 default_server 去处理请求。

如果没有 defautl_server, 会找第一个端口能匹配上的 server 去处理请求。

如果要禁止非法 server_name 的请求,可以配置一个空的 default_server 来处理非法请求.

server {
    listen 80 default_server;
    listen 443 ssl default_server;
    ssl_reject_handshake on;

    server_name _
}
fangmd commented 6 months ago

设置默认 server

防止非法域名的访问

    server {
       listen 80 default_server;
       listen 443 default_server;
       server_name _;

    ssl_certificate "/usr/Nginx/cert.pem";
    ssl_certificate_key "/usr/Nginx/key.pem";
    ssl_session_cache shared:SSL:1m;
    ssl_session_timeout  10m;
    ssl_ciphers HIGH:!aNULL:!MD5;
    ssl_prefer_server_ciphers on;
       return 403;
    }