nginx 常用配置

100 阅读1分钟

接口请求转发、vue history 模式配置、静态文件代理、websocket代理、允许跨域配置

server {
    listen       80;
    listen  [::]:80;
    server_name  localhost;
    
    # 匹配根路由
    location / {
        # root指定静态资源根路径
        root   /usr/share/nginx/html;
        # index指定入口文件
        index  index.html index.htm;
    }
    
    # 接口请求转发
    location /api/ {
      proxy_pass http://36.133.182.60:8004/api/;
    }
    
    # vue history 模式的配置
    location /qkmain/ {
        # 指定静态资源根路径
        root         /usr/share/nginx/html/;
        # 将/qkmain/开头的路径代理到 根路径+/qkmain/index.html 文件下
        try_files $uri $uri/ /qkmain/index.html;
    }
    
    # 将服务器某个文件夹下的静态资源通过nginx代理出去
    # 被代理的文件夹可能需要添加权限
    location /image/ {
        # alias指定静态资源路径
        alias  /home/img/;
        index  index.html;
        autoindex on;
    }
    
    # 代理 websocket
    location /ws/ {
        proxy_pass http://dcp-server:8090/ws/;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "upgrade";
    }
    
    # 访问某个路径时允许跨域
    location /qkvue/ {
        # 允许访问的域名,*为全部
        add_header 'Access-Control-Allow-Origin' '*';
        add_header 'Access-Control-Allow-Credentials' 'true';
        # 允许的请求类型
        add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
        # 允许携带的请求头
        add_header 'Access-Control-Allow-Headers' 'DNT,web-token,app-token,Authorization,Accept,Origin,Keep-Alive,User-Agent,X-Mx-ReqToken,X-Data-Type,X-Auth-Token,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range';
        add_header 'Access-Control-Expose-Headers' 'Content-Length,Content-Range';
        # 请求类型为OPTIONS时的处理
        if ($request_method = 'OPTIONS') {
            add_header 'Access-Control-Max-Age' 1728000;
            add_header 'Content-Type' 'text/plain; charset=utf-8';
            add_header 'Content-Length' 0;
            return 204;
        }
        
        # 访问qkvue时代理的静态资源根目录
        root         /usr/share/nginx/html/;
        # history 模式相应的配置
        try_files $uri $uri/ /qkvue/index.html;
    }


    error_page   500 502 503 504  /50x.html;
    location = /50x.html {
        root   /usr/share/nginx/html;
    }
}

nginx 路径的匹配规则, 优先级按照从高到低

  • location = /xxx: 路径精确匹配
  • location ^~ /xxx: 路径前缀匹配
  • location ~ xxx: 路径正则匹配
  • location ~* xxx: 路径正则匹配, 不区分大小写, 与正则匹配的优先级相同
  • location /xxx : 路径前缀匹配
  • location / : 通用匹配, 当其他都没有匹配的时候, 会走到这里.

nginx会按照优先级从高到低依次进行匹配, 在第一个匹配成功的时候执行操作并停止匹配.