# Nginx 速查表

# 基本结构

worker_processes 1;

events {
  worker_connections 1024;
}

http {
  
  include mime.types;
  default_type application/octet-stream;
  sendfile on;
  keepalive_timeout 60;

  server {
    listen 80;
    listen 443;
    server_name localhost;
    
    # entry
    root /usr/share/nginx/html;
    index index.php index.html index.htm default.php default.htm default.html;
    
    # spa history router
    location / {
      root /app;
      try_files $uri $uri/ /index.html;
      index index.html index.htm;
    }

    # log
    access_log /var/log/nginx/host.access.log;
    error_log /var/log/nginx/error.log;
  }
}

# 跨域代理

可以通过

  • http://a.com?URL=http://b.com/a.mp4
  • http://a.com/_proxy/http://b.com/a.mp4

转发到

  • http://b.com/a.mp4
server {
    listen 80;
    server_name proxy.domain.com; 

    # match _proxy
    location ~* ^/_proxy/ {

      # 能解析转发 URL 的 DNS
      resolver 114.114.114.114;

      # request uri 
      if ( $request_uri ~ "(/|=)(http.*)" ) {
          set $proxy_url $2;
      }  
    
      # get host
      set $proxy_host $host; 
      if ( $proxy_url ~ "https?://(.*?)/" ) {
          set $proxy_host $1;
      } 
        
      # proxy
      proxy_pass $proxy_url;
      proxy_set_header Host $proxy_host;
      proxy_set_header X-Forwarded-For $remote_addr;
      # range
      proxy_cache_key $host&uri&is_args&args$http_range;
      proxy_set_header Range $http_range;
      proxy_set_header If-Range $http_if_range;
      proxy_cache_valid 200 206; 
      # cache
      add_header expires max;
    }

    # cors
    add_header "Access-Control-Allow-Origin"  *;
    add_header "Access-Control-Allow-Methods" *;
    add_header "Access-Control-Allow-Headers" "Authorization, Origin, Content-Type, Accept";
    # log
    access_log  /www/wwwlogs/api.gausszhou.top.log;
    error_log  /www/wwwlogs/api.gausszhou.top.error.log;
}

Nginx中如何对地址参数进行代理 (opens new window) Nginx中如何对范围请求进行处理 (opens new window)