前端生产nginx配置代理

185 阅读1分钟

参考文章:nginx 之 proxy_pass详解 - 简书 (jianshu.com)

server{
    server_name _; #表示匹配所有域名
    #listen 80; #80 不用写
    client_max_body_size 100M; # 默认限制上传附件大小
    
    # ~* 为不区分大小写正则匹配,后面跟的正则表达式指以该后缀结尾
    location ~* \.(?:jpg|jpeg|png|gif|ico|css|js)$ {
      #配置跨域请求
      add_header Access-Control-Allow-Origin *;
      add_header Access-Control-Allow-Methods 'GET, POST, OPTIONS';
      add_header Access-Control-Allow-Headers 'DNT,X-Mx-ReqToken,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Authorization';
      
      root /home/app;
      expires 365d;#缓存365天
      add_header Cache-Control "public"; #可以被任何缓存区缓存, 如: 浏览器、服务器、代理服务器等.
      add_header Nginx-Cache "$upstream_cache_status"; #缓存命中分析
    } 

    location ~ ^/(static|css|js|img)/ {
      add_header Access-Control-Allow-Origin *;
      add_header Access-Control-Allow-Methods 'GET, POST, OPTIONS';
      add_header Access-Control-Allow-Headers 'DNT,X-Mx-ReqToken,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Authorization';
      root /home/app;
    }

    # 代理ajax请求
    # location ^~/api {
    #    rewrite ^/api/(.*)$ /$1 break; # 如果后端接口不是统一以api开头,去掉api前缀
    #    proxy_pass http://api_service/;
    #    proxy_set_header Host  $http_host;
    #    proxy_set_header Connection close;
    #    proxy_set_header X-Real-IP $remote_addr;
    #    proxy_set_header X-Forwarded-Server $host;
    # }
    location / {
      root /home/app;
      index index.html;
      try_files $uri $uri/ /index.html =404;#依次匹配 $uri、$uri 路径下的资源,如果没有,则匹配 404

      #禁止缓存
      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;
    }
    location /api {
      # 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_pass http://backend-url.com;
    } 
    # error_page 404 /404.html;
    #   location = /40x.html {
    # }
    # error_page 500 502 503 504 /50x.html;
    #   location = /50x.html {
    # }
}