首页 > 技术文章 > Nginx 使用小结

mrguoguo 2020-08-12 13:01 原文

1.   80端口公用问题  多个域名访问

http {
include mime.types;
#公用80端口//就这里加一行就可以了
include /etc/nginx/vhosts/*.conf;
default_type application/octet-stream;
....
}

  1 #user  nobody;
  2 worker_processes  4; #nginx进程数,建议设置为等于CPU总核心数
  3 
  4 #error_log  logs/error.log;
  5 #error_log  logs/error.log  notice;
  6 #error_log  logs/error.log  info;
  7 
  8 #pid        logs/nginx.pid;
  9 
 10 
 11 events {
 12     worker_connections  1024; #单个进程最大连接数(最大连接数=连接数*进程数)
 13 }
 14 
 15 
 16 http {
 17     include       mime.types;
 18     #公用80端口//就这里加一行就可以了
 19     include /etc/nginx/vhosts/*.conf;  
 20     default_type  application/octet-stream;
 21 
 22     #log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
 23     #                  '$status $body_bytes_sent "$http_referer" '
 24     #                  '"$http_user_agent" "$http_x_forwarded_for"';
 25 
 26     #access_log  logs/access.log  main;
 27 
 28     sendfile        on;
 29     #tcp_nopush     on;
 30 
 31     #keepalive_timeout  0;
 32     keepalive_timeout  65;
 33 
 34     #gzip  on;
 35 
 36     #服务器集群名称为Jq_one
 37     upstream test.cn {
 38     #server  127.0.0.1:9000; 
 39     #server  127.0.0.1:8082; 
 40       server 127.0.0.1:8087; #weight=2 max_fails=2 fail_timeout=2;
 41       server 127.0.0.1:8086; #weight=1 max_fails=2 fail_timeout=1; 
 42       ip_hash;
 43     }
 44 
 45     server {
 46         listen       80;
 47         server_name  test.cn;
 48 
 49         #listen       80;   #//注意这里,要把默认的那个default_server去掉,因为我们在下面要单独配置域名访问,所以这里不要留default_server,不然会报错。
 50         #server_name  mytest.com  mytest111.com;  //这里写你想设置的域名,可以写多个,对应多个server 和多个upstream与名之间用空格隔开
 51         #root         /mnt/share/mytest.com;   //这里是你虚拟机的根目录,写绝对路径
 52         
 53         
 54         
 55         #charset koi8-r;
 56         #access_log  logs/host.access.log  main;
 57 
 58         location / {
 59             root   /;
 60             index  index.aspx index.html index.htm default.aspx;
 61         #指向集群名称为Jq_one  (这里需要在C:\Windows\System32\drivers\etc\hosts文件中添加设置,否则有可能使用ngintest.com访问时无法使用 如代码下面的图。其中ngintest.com也是设置服务器集群的名称)
 62         proxy_pass         http://test.cn; 
 63         #设置主机头和客户端真实地址,以便服务器获取客户端真实IP
 64             proxy_set_header X-Forwarded-Host $host;
 65             proxy_set_header X-Forwarded-Server $host;
 66             proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
 67             proxy_set_header  X-Real-IP  $remote_addr; 
 68         }
 69 
 70     #静态资源缓存设置
 71     
 72         location ~ .*\.(gif|jpg|jpeg|png|bmp|swf|flv|ico|svg|htm)$ {
 73             root F:/ftp/himall2.8/;
 74             expires 7d;            
 75             access_log off;
 76         }
 77  
 78  
 79         location ~ .*\.(js|css)?$ {
 80             root F:/ftp/himall2.8/;
 81             expires 1d;            
 82             access_log off;
 83         }
 84 
 85         error_page  404              /404.html;
 86 
 87         # redirect server error pages to the static page /50x.html
 88         #
 89         error_page   500 502 503 504  /50x.html;
 90         location = /50x.html {
 91             root   html;
 92         }
 93 
 94         # proxy the PHP scripts to Apache listening on 127.0.0.1:80
 95         #
 96         #location ~ \.php$ {
 97         #    proxy_pass   http://127.0.0.1;
 98         #}
 99 
100         # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
101         #
102         #location ~ \.php$ {
103         #    root           html;
104         #    fastcgi_pass   127.0.0.1:9000;
105         #    fastcgi_index  index.php;
106         #    fastcgi_param  SCRIPT_FILENAME  /scripts$fastcgi_script_name;
107         #    include        fastcgi_params;
108         #}
109 
110         # deny access to .htaccess files, if Apache's document root
111         # concurs with nginx's one
112         #
113         #location ~ /\.ht {
114         #    deny  all;
115         #}
116     }
117 
118 
119     # another virtual host using mix of IP-, name-, and port-based configuration
120     #
121     #server {
122     #    listen       8000;
123     #    listen       somename:8080;
124     #    server_name  somename  alias  another.alias;
125 
126     #    location / {
127     #        root   html;
128     #        index  index.html index.htm;
129     #    }
130     #}
131 
132 
133     # HTTPS server
134     #
135     #server {
136     #    listen       443 ssl;
137     #    server_name  localhost;
138 
139     #    ssl_certificate      cert.pem;
140     #    ssl_certificate_key  cert.key;
141 
142     #    ssl_session_cache    shared:SSL:1m;
143     #    ssl_session_timeout  5m;
144 
145     #    ssl_ciphers  HIGH:!aNULL:!MD5;
146     #    ssl_prefer_server_ciphers  on;
147 
148     #    location / {
149     #        root   html;
150     #        index  index.html index.htm;
151     #    }
152     #}
153 
154 }
View Code

 

2.  数据流转发  例如 程序部署在 sever 1  ,sever0 做负载均衡,那么直接可以把数据流全量转发 https 好像也能按域名转发(没有实验)

stream {
server {
listen 443;
proxy_connect_timeout 5s;
proxy_timeout 10s;
proxy_pass 192.168.2.230:4431;
}
}

  1 #user  nobody;
  2 worker_processes  1;
  3 
  4 #error_log  logs/error.log;
  5 #error_log  logs/error.log  notice;
  6 #error_log  logs/error.log  info;
  7 
  8 #pid        logs/nginx.pid;
  9 
 10 events {
 11     worker_connections  1024;
 12 }
 13 
 14 stream {
 15     server {
 16        listen 443; 
 17        proxy_connect_timeout 5s;
 18        proxy_timeout 10s;
 19        proxy_pass 192.168.2.230:4431;    
 20     }
 21 }
 22 
 23 http {
 24     include       mime.types;
 25     default_type  application/octet-stream;
 26 
 27     #log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
 28     #                  '$status $body_bytes_sent "$http_referer" '
 29     #                  '"$http_user_agent" "$http_x_forwarded_for"';
 30 
 31     #access_log  logs/access.log  main;
 32 
 33     sendfile        on;
 34     #tcp_nopush     on;
 35 
 36     #keepalive_timeout  0;
 37     keepalive_timeout  65;
 38 
 39     #gzip  on;
 40 
 41     server {
 42         listen       8080;
 43         server_name  localhost;
 44     sendfile        on;
 45     #tcp_nopush     on;
 46 
 47     #keepalive_timeout  0;
 48     keepalive_timeout  65;
 49 
 50     #gzip  on;
 51         #charset koi8-r;
 52 
 53         #access_log  logs/host.access.log  main;
 54 
 55         location / {
 56             add_header Access-Control-Allow-Origin *;
 57     add_header Access-Control-Allow-Methods 'GET,POST';
 58     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'; 
 59             root   html;
 60             index  index.html index.htm;
 61         }
 62         
 63          location ~* \.mp4$ {  #这里就是最重要的配置
 64              add_header Access-Control-Allow-Origin *;
 65     add_header Access-Control-Allow-Methods 'GET,POST';
 66     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'; 
 67        root D:/; #这里是你的视频的存放目录
 68         }
 69 
 70         #error_page  404              /404.html;
 71 
 72         # redirect server error pages to the static page /50x.html
 73         #
 74         error_page   500 502 503 504  /50x.html;
 75         location = /50x.html {
 76             root   html;
 77         }
 78 
 79         # proxy the PHP scripts to Apache listening on 127.0.0.1:80
 80         #
 81         #location ~ \.php$ {
 82         #    proxy_pass   http://127.0.0.1;
 83         #}
 84 
 85         # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
 86         #
 87         #location ~ \.php$ {
 88         #    root           html;
 89         #    fastcgi_pass   127.0.0.1:9000;
 90         #    fastcgi_index  index.php;
 91         #    fastcgi_param  SCRIPT_FILENAME  /scripts$fastcgi_script_name;
 92         #    include        fastcgi_params;
 93         #}
 94 
 95         # deny access to .htaccess files, if Apache's document root
 96         # concurs with nginx's one
 97         #
 98         #location ~ /\.ht {
 99         #    deny  all;
100         #}
101     }
102 
103 
104     # another virtual host using mix of IP-, name-, and port-based configuration
105     #
106     #server {
107     #    listen       8000;
108     #    listen       somename:8080;
109     #    server_name  somename  alias  another.alias;
110 
111     #    location / {
112     #        root   html;
113     #        index  index.html index.htm;
114     #    }
115     #}
116 
117 
118     # HTTPS server
119     #
120     #server {
121     #    listen       443 ssl;
122     #    server_name  localhost;
123 
124     #    ssl_certificate      cert.pem;
125     #    ssl_certificate_key  cert.key;
126 
127     #    ssl_session_cache    shared:SSL:1m;
128     #    ssl_session_timeout  5m;
129 
130     #    ssl_ciphers  HIGH:!aNULL:!MD5;
131     #    ssl_prefer_server_ciphers  on;
132 
133     #    location / {
134     #        root   html;
135     #        index  index.html index.htm;
136     #    }
137     #}
138 
139 }
View Code

 

3. 视频直播点播 rtmp 配置 (前提是 安装了 Nginx-Rtmp-Module 模块)

https://github.com/NodeMedia/NodeMediaDevClient

 

  1 #user  nobody;
  2 # multiple workers works !
  3 worker_processes  1;
  4 
  5 #error_log  logs/error.log;
  6 #error_log  logs/error.log  notice;
  7 #error_log  logs/error.log  info;
  8 
  9 #pid        logs/nginx.pid;
 10 
 11 events {
 12     worker_connections  1024;
 13     # max value 32768, nginx recycling connections+registry optimization = 
 14     #   this.value * 20 = max concurrent connections currently tested with one worker
 15     #   C1000K should be possible depending there is enough ram/cpu power
 16     # multi_accept on;
 17 }
 18 
 19 rtmp {
 20     server {
 21         listen 1935;
 22         chunk_size 4096;
 23         max_message 5M;
 24         
 25         application live {
 26              live on;
 27              record off;
 28              drop_idle_publisher 10s;
 29         }
 30         
 31         application save {
 32              live on;
 33              drop_idle_publisher 10s;
 34              
 35              #设置录制属性
 36              recorder rec{
 37              record all;                       #录制视频和音频
 38              record_path D:/work/nginx/nginx-rtmp-win32/tmp/rec;
 39              record_unique on;                                   #是否添加时间戳到录制文件。否则的话同样的文件在每一次新的录制发生时将被重写。默认为 off
 40              record_suffix .mp4;
 41              #record_suffix -%d-%b-%y-%T.flv;                     #设置录制文件后缀名。默认为 '.flv'
 42              #record_max_frames 1800;                             #设置每个录制文件的视频帧的最大数量
 43              record_interval 1m;                    #在这个指令指定数量的(毫秒)秒之后重启录制
 44              }
 45         }
 46         
 47         application hls {  
 48             live on;  
 49             hls on;  
 50             hls_path tmp/hls;  
 51             #hls_fragment 5s;
 52             #hls_playlist_length 15s;
 53             #hls_continuous on; #连续模式。
 54             #hls_cleanup on;    #对多余的切片进行删除。
 55             #hls_nested on;     #嵌套模式。
 56         } 
 57         
 58         application vod {
 59             play tmp/video;
 60         }
 61         
 62     #    application src {
 63      #        live on;
 64     #         record off;
 65     #         drop_idle_publisher 10s;
 66         #     exec ffmpeg.exe -i rtmp://localhost/src/$name -c copy -f flv rtmp://localhost/live/$name 2>>./ffmpeg-$name.log;
 67      #   }
 68     }
 69 }
 70 
 71 http {
 72     #include      /nginx/conf/naxsi_core.rules;
 73     include       mime.types;
 74     default_type  application/octet-stream;
 75 
 76     #log_format  main  '$remote_addr:$remote_port - $remote_user [$time_local] "$request" '
 77     #                  '$status $body_bytes_sent "$http_referer" '
 78     #                  '"$http_user_agent" "$http_x_forwarded_for"';
 79 
 80     #access_log  logs/access.log  main;
 81 
 82 #     # loadbalancing PHP
 83 #     upstream myLoadBalancer {
 84 #         server 127.0.0.1:9001 weight=1 fail_timeout=5;
 85 #         server 127.0.0.1:9002 weight=1 fail_timeout=5;
 86 #         server 127.0.0.1:9003 weight=1 fail_timeout=5;
 87 #         server 127.0.0.1:9004 weight=1 fail_timeout=5;
 88 #         server 127.0.0.1:9005 weight=1 fail_timeout=5;
 89 #         server 127.0.0.1:9006 weight=1 fail_timeout=5;
 90 #         server 127.0.0.1:9007 weight=1 fail_timeout=5;
 91 #         server 127.0.0.1:9008 weight=1 fail_timeout=5;
 92 #         server 127.0.0.1:9009 weight=1 fail_timeout=5;
 93 #         server 127.0.0.1:9010 weight=1 fail_timeout=5;
 94 #         least_conn;
 95 #     }
 96 
 97     sendfile        off;
 98     #tcp_nopush     on;
 99 
100     server_names_hash_bucket_size 128;
101 
102 ## Start: Timeouts ##
103     client_body_timeout   10;
104     client_header_timeout 10;
105     keepalive_timeout     30;
106     send_timeout          10;
107     keepalive_requests    10;
108 ## End: Timeouts ##
109 
110     #gzip  on;
111 
112     server {
113         listen       8080;
114         server_name  localhost;
115 
116 
117         location /stat {
118             rtmp_stat all;
119             rtmp_stat_stylesheet stat.xsl;
120         }
121         #location /stat.xsl {
122          #   root nginx-rtmp-module/;
123         #}
124         location /stat.xsl {
125             root html/;
126         }
127         location /control {
128             rtmp_control all;
129         }
130         
131         location /hls {  
132             types {  
133                 application/vnd.apple.mpegurl m3u8;  
134                 video/mp2t ts;  
135             }  
136             root tmp/;  
137             add_header Cache-Control no-cache; 
138             #访问权限开启,否则访问这个地址会报403
139             #autoindex on;
140             #alias /usr/local/vod/hls;#视频流存放地址,与上面的hls_path相对应,这里root和alias的区别可自行百度
141             #expires -1;
142             
143             #防止跨域问题
144             #add_header 'Access-Control-Allow-Origin' '*';
145             #add_header 'Access-Control-Allow-Credentials' 'true';
146             #add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
147             #add_header 'Access-Control-Allow-Headers' 'DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type';            
148         }
149 
150         #charset koi8-r;
151         #access_log  logs/host.access.log  main;
152 
153         ## Caching Static Files, put before first location
154         #location ~* \.(jpg|jpeg|png|gif|ico|css|js)$ {
155         #    expires 14d;
156         #    add_header Vary Accept-Encoding;
157         #}
158 
159 # For Naxsi remove the single # line for learn mode, or the ## lines for full WAF mode
160         location / {
161             #include    /nginx/conf/mysite.rules; # see also http block naxsi include line
162             ##SecRulesEnabled;
163          ##DeniedUrl "/RequestDenied";
164          ##CheckRule "$SQL >= 8" BLOCK;
165          ##CheckRule "$RFI >= 8" BLOCK;
166          ##CheckRule "$TRAVERSAL >= 4" BLOCK;
167          ##CheckRule "$XSS >= 8" BLOCK;
168             root   html;
169             index  index.html index.htm;
170         }
171 
172 # For Naxsi remove the ## lines for full WAF mode, redirect location block used by naxsi
173         ##location /RequestDenied {
174         ##    return 412;
175         ##}
176 
177 ## Lua examples !
178 #         location /robots.txt {
179 #           rewrite_by_lua '
180 #             if ngx.var.http_host ~= "localhost" then
181 #               return ngx.exec("/robots_disallow.txt");
182 #             end
183 #           ';
184 #         }
185 
186         #error_page  404              /404.html;
187 
188         # redirect server error pages to the static page /50x.html
189         #
190         error_page   500 502 503 504  /50x.html;
191         location = /50x.html {
192             root   html;
193         }
194 
195         # proxy the PHP scripts to Apache listening on 127.0.0.1:80
196         #
197         #location ~ \.php$ {
198         #    proxy_pass   http://127.0.0.1;
199         #}
200 
201         # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
202         #
203         #location ~ \.php$ {
204         #    root           html;
205         #    fastcgi_pass   127.0.0.1:9000; # single backend process
206         #    fastcgi_pass   myLoadBalancer; # or multiple, see example above
207         #    fastcgi_index  index.php;
208         #    fastcgi_param  SCRIPT_FILENAME  $document_root$fastcgi_script_name;
209         #    include        fastcgi_params;
210         #}
211 
212         # deny access to .htaccess files, if Apache's document root
213         # concurs with nginx's one
214         #
215         #location ~ /\.ht {
216         #    deny  all;
217         #}
218     }
219 
220     # another virtual host using mix of IP-, name-, and port-based configuration
221     #
222     #server {
223     #    listen       8000;
224     #    listen       somename:8080;
225     #    server_name  somename  alias  another.alias;
226 
227     #    location / {
228     #        root   html;
229     #        index  index.html index.htm;
230     #    }
231     #}
232 
233     # HTTPS server
234     #
235     #server {
236     #    listen       443 ssl spdy;
237     #    server_name  localhost;
238 
239     #    ssl                  on;
240     #    ssl_certificate      cert.pem;
241     #    ssl_certificate_key  cert.key;
242     #    ssl_session_timeout  5m;
243     #    ssl_prefer_server_ciphers On;
244     #    ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
245     #    ssl_ciphers ECDH+AESGCM:ECDH+AES256:ECDH+AES128:ECDH+3DES:RSA+AESGCM:RSA+AES:RSA+3DES:!aNULL:!eNULL:!MD5:!DSS:!EXP:!ADH:!LOW:!MEDIUM;
246 
247     #    location / {
248     #        root   html;
249     #        index  index.html index.htm;
250     #    }
251     #}
252 
253 }
View Code

4. 常用 功能说明

 1 ########### 每个指令必须有分号结束。#################
 2 #user administrator administrators;  #配置用户或者组,默认为nobody nobody。
 3 #worker_processes 2;  #允许生成的进程数,默认为1
 4 #pid /nginx/pid/nginx.pid;   #指定nginx进程运行文件存放地址
 5 error_log log/error.log debug;  #制定日志路径,级别。这个设置可以放入全局块,http块,server块,级别以此为:debug|info|notice|warn|error|crit|alert|emerg
 6 events {
 7     accept_mutex on;   #设置网路连接序列化,防止惊群现象发生,默认为on
 8     multi_accept on;  #设置一个进程是否同时接受多个网络连接,默认为off
 9     #use epoll;      #事件驱动模型,select|poll|kqueue|epoll|resig|/dev/poll|eventport
10     worker_connections  1024;    #最大连接数,默认为512
11 }
12 http {
13     include       mime.types;   #文件扩展名与文件类型映射表
14     default_type  application/octet-stream; #默认文件类型,默认为text/plain
15     #access_log off; #取消服务日志    
16     log_format myFormat '$remote_addr–$remote_user [$time_local] $request $status $body_bytes_sent $http_referer $http_user_agent $http_x_forwarded_for'; #自定义格式
17     access_log log/access.log myFormat;  #combined为日志格式的默认值
18     sendfile on;   #允许sendfile方式传输文件,默认为off,可以在http块,server块,location块。
19     sendfile_max_chunk 100k;  #每个进程每次调用传输数量不能大于设定的值,默认为0,即不设上限。
20     keepalive_timeout 65;  #连接超时时间,默认为75s,可以在http,server,location块。
21 
22     upstream mysvr {   
23       server 127.0.0.1:7878;
24       server 192.168.10.121:3333 backup;  #热备
25     }
26     error_page 404 https://www.baidu.com; #错误页
27     server {
28         keepalive_requests 120; #单连接请求上限次数。
29         listen       4545;   #监听端口
30         server_name  127.0.0.1;   #监听地址       
31         location  ~*^.+$ {       #请求的url过滤,正则匹配,~为区分大小写,~*为不区分大小写。
32            #root path;  #根目录
33            #index vv.txt;  #设置默认页
34            proxy_pass  http://mysvr;  #请求转向mysvr 定义的服务器列表
35            deny 127.0.0.1;  #拒绝的ip
36            allow 172.18.5.54; #允许的ip           
37         } 
38     }
39 }
View Code
 1 include       mime.types;   #文件扩展名与文件类型映射表
 2     default_type  application/octet-stream; #默认文件类型,默认为text/plain
 3     #access_log off; #取消服务日志    
 4     log_format myFormat ' $remote_addr–$remote_user [$time_local] $request $status $body_bytes_sent $http_referer $http_user_agent $http_x_forwarded_for'; #自定义格式
 5     access_log log/access.log myFormat;  #combined为日志格式的默认值
 6     sendfile on;   #允许sendfile方式传输文件,默认为off,可以在http块,server块,location块。
 7     sendfile_max_chunk 100k;  #每个进程每次调用传输数量不能大于设定的值,默认为0,即不设上限。
 8     keepalive_timeout 65;  #连接超时时间,默认为75s,可以在http,server,location块。
 9     proxy_connect_timeout 1;   #nginx服务器与被代理的服务器建立连接的超时时间,默认60秒
10     proxy_read_timeout 1; #nginx服务器想被代理服务器组发出read请求后,等待响应的超时间,默认为60秒。
11     proxy_send_timeout 1; #nginx服务器想被代理服务器组发出write请求后,等待响应的超时间,默认为60秒。
12     proxy_http_version 1.0 ; #Nginx服务器提供代理服务的http协议版本1.01.1,默认设置为1.0版本。
13     #proxy_method get;    #支持客户端的请求方法。post/get;
14     proxy_ignore_client_abort on;  #客户端断网时,nginx服务器是否终端对被代理服务器的请求。默认为off。
15     proxy_ignore_headers "Expires" "Set-Cookie";  #Nginx服务器不处理设置的http相应投中的头域,这里空格隔开可以设置多个。
16     proxy_intercept_errors on;    #如果被代理服务器返回的状态码为400或者大于400,设置的error_page配置起作用。默认为off。
17     proxy_headers_hash_max_size 1024; #存放http报文头的哈希表容量上限,默认为512个字符。
18     proxy_headers_hash_bucket_size 128; #nginx服务器申请存放http报文头的哈希表容量大小。默认为64个字符。
19     proxy_next_upstream timeout;  #反向代理upstream中设置的服务器组,出现故障时,被代理服务器返回的状态值。error|timeout|invalid_header|http_500|http_502|http_503|http_504|http_404|off
20     #proxy_ssl_session_reuse on; 默认为on,如果我们在错误日志中发现“SSL3_GET_FINSHED:digest check failed”的情况时,可以将该指令设置为off。
View Code

 

推荐阅读