nginx实战

1、安装流程

# 安装相关依赖
yum -y install make zlib zlib-devel gcc-c++ libtool  openssl openssl-devel

# 下载安装包
wget http://nginx.org/download/nginx-1.15.9.tar.gz

# 解压
tar -zxvf nginx-1.15.9.tar.gz

cd nginx-1.15.9

./configure --prefix=/usr/local/nginx/ \
--with-http_ssl_module --with-http_stub_status_module

make && make install

cd /usr/local/nginx/sbin
# 启动
./nginx -c /usr/local/nginx/conf/nginx.conf
# 结束
./nginx -s stop

2、nginx.conf配置文件简介

[root@localhost nginx]# vim nginx.conf

# 设置 nginx服务的系统使用用户和用户组
user nginx root;

# 工作进程数,等同于CPU的总核心数
worker_processes  8;

# 定义全局错误日志定义类型,[debug|info|notice|warn|crit]
error_log  /var/log/nginx/error.log warn;
error_log  /var/log/nginx/notice.log  notice;
error_log  /var/log/nginx/info.log  info;
.....

# 进程文件
pid /var/run/nginx.pid;

# 进程最大打开文件数
worker_rlimit_nofile 65535;

# 工作模式及连接数上限
events {

	# 参考事件模型,use [ kqueue | rtsig | epoll | /dev/poll | select | poll ]; 
	# epoll模型是Linux 2.6以上版本内核中的高性能网络I/O模型,如果跑在FreeBSD上面,就用kqueue模型
    use epoll;
	
	# 每个进程允许最大连接数
    worker_connections  65535;
}

# 设定http服务器,利用它的反向代理功能提供负载均衡支持
http
{
    include mime.types; # 文件扩展名与文件类型映射表
    default_type application/octet-stream; # 默认文件类型
    #charset utf-8; # 默认编码
    server_names_hash_bucket_size 128; # 服务器名字的hash表大小
    client_header_buffer_size 32k; #上传文件大小限制
    large_client_header_buffers 4 64k; # 设定请求缓
    client_max_body_size 8m; # 设定请求缓
    
    # 开启目录列表访问,合适下载服务器,默认关闭.
    autoindex on; # 显示目录
    autoindex_exact_size on; # 显示文件大小 默认为on,显示出文件的确切大小,单位是bytes 改为off后,显示出文件的大概大小,单位是kB或者MB或者GB
    autoindex_localtime on; # 显示文件时间 默认为off,显示的文件时间为GMT时间 改为on后,显示的文件时间为文件的服务器时间
    
    sendfile on; # 开启高效文件传输模式,sendfile指令指定nginx是否调用sendfile函数来输出文件,对于普通应用设为 on,如果用来进行下载等应用磁盘IO重负载应用,可设置为off,以平衡磁盘与网络I/O处理速度,降低系统的负载.注意:如果图片显示不正常把这个改成off.
    tcp_nopush on; # 防止网络阻塞
    tcp_nodelay on; # 防止网络阻塞
    
    keepalive_timeout 120; # (单位s)设置客户端连接保持活动的超时时间,在超过这个时间后服务器会关闭该链接
    
    # FastCGI相关参数是为了改善网站的性能:减少资源占用,提高访问速度.下面参数看字面意思都能理解.
    fastcgi_connect_timeout 300;
    fastcgi_send_timeout 300;
    fastcgi_read_timeout 300;
    fastcgi_buffer_size 64k;
    fastcgi_buffers 4 64k;
    fastcgi_busy_buffers_size 128k;
    fastcgi_temp_file_write_size 128k;
    
    # gzip模块设置
    gzip on; #开启gzip压缩输出
    gzip_min_length 1k; #允许压缩的页面的最小字节数,页面字节数从header偷得content-length中获取.默认是0,不管页面多大都进行压缩.建议设置成大于1k的字节数,小于1k可能会越压越大
    gzip_buffers 4 16k; #表示申请4个单位为16k的内存作为压缩结果流缓存,默认值是申请与原始数据大小相同的内存空间来存储gzip压缩结果
    gzip_http_version 1.1; #压缩版本(默认1.1,目前大部分浏览器已经支持gzip解压.前端如果是squid2.5请使用1.0)
    gzip_comp_level 2; #压缩等级.1压缩比最小,处理速度快.9压缩比最大,比较消耗cpu资源,处理速度最慢,但是因为压缩比最大,所以包最小,传输速度快
    gzip_types text/plain application/x-javascript text/css application/xml;
    #压缩类型,默认就已经包含text/html,所以下面就不用再写了,写上去也不会有问题,但是会有一个warn.
    gzip_vary on;#选项可以让前端的缓存服务器缓存经过gzip压缩的页面.例如:用squid缓存经过nginx压缩的数据
    
    #开启限制IP连接数的时候需要使用
    #limit_zone crawler $binary_remote_addr 10m;
    
    ##upstream的负载均衡,四种调度算法(下例主讲)##
    
    #虚拟主机的配置
    server
    {
        # 监听端口
        listen 80;
        # 域名可以有多个,用空格隔开
        server_name localhost www.xxx.com;
        # HTTP 自动跳转 HTTPS
        rewrite ^(.*) https://$server_name$1 permanent;
    }
    
    server
    {
        # 监听端口 HTTPS
        listen 443 ssl;
        server_name ably.com;
        
        #代理配置参数
        proxy_connect_timeout 180;
        proxy_send_timeout 180;
        proxy_read_timeout 180;
        proxy_set_header Host $host;
        proxy_set_header X-Forwarder-For $remote_addr;
        
        # 配置域名证书
        ssl_certificate      C:\WebServer\Certs\certificate.crt;
        ssl_certificate_key  C:\WebServer\Certs\private.key;
        ssl_session_cache    shared:SSL:1m;
        ssl_session_timeout  5m;
        ssl_protocols SSLv2 SSLv3 TLSv1;
        ssl_ciphers ALL:!ADH:!EXPORT56:RC4+RSA:+HIGH:+MEDIUM:+LOW:+SSLv2:+EXP;
        ssl_prefer_server_ciphers  on;
    	
    	# 首页
        index index.html index.htm index.php;
        root /data/www/;
        location ~ .*\.(php|php5)?$
        {
            fastcgi_pass 127.0.0.1:9000;
            fastcgi_index index.php;
            include fastcgi.conf;
        }
        
        # 配置地址拦截转发,解决跨域验证问题
        location /oauth/{
            proxy_pass https://localhost:13580/oauth/;
            proxy_set_header HOST $host;
            proxy_set_header X-Real-IP $remote_addr;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        }
        
        # 图片缓存时间设置
        location ~ .*\.(gif|jpg|jpeg|png|bmp|swf)$ {
            expires 10d;
        }
        
        # 静态文件,nginx自己处理
        # = :进行普通精准匹配
		# ^~:以什么什么开头
		# ~^\~*:以正则表达式匹配
        location ~ ^/(images|javascript|js|css|flash|media|static)/ {
        	# 页面首页的路径
            root /opt/images;
            # 过期30天,静态文件不怎么更新,过期可以设大一点,如果频繁更新,则可以设置得小一点。
            expires 30d;
        }
        
        #禁止访问 .htxxx 文件
        location ~ /\.ht {
            deny all;
        }

        # 日志格式设定
        log_format access '$remote_addr - $remote_user [$time_local] "$request" '
        '$status $body_bytes_sent "$http_referer" '
        '"$http_user_agent" $http_x_forwarded_for';
        
        # 定义本虚拟主机的访问日志
        access_log /var/log/nginx/access.log access;
        
        # 反向代理的路径(和upstream绑定),location 后面设置映射的路径
        location / {
            proxy_pass http://ip;
        }
        
        # 返回错误的页面
        error_page   500 502 503 504 404 /50x.html;
        location = /50x.html {
            # 50x页面所对应的位置
            # root表示的是完整的路径
            # alias表示简洁的路径
            root   /usr/share/nginx/html;
        }
        
    }
}

3、查看配置文件编写是否合法

[root@localhost nginx]# nginx -t
# 显示以下内容就证明配置文件配置没有问题,一旦报错请检查配置文件是否正确
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful

4、请求IP

[root@localhost nginx]# curl -v http://www.baidu.com >/dev/null

5、查看客户端的状态

# 配置
location /mystatus {
  stub_status;
}
# 访问:http://192.168.86.128/mystatus
# nginx当前活跃状态数
Active connections: 1
server accepts handled requests
# 握手的次数 链接的次数 总的请求数
 1           1          1
# 读的数  写的数     等待的数
Reading: 0 Writing: 1 Waiting: 0

6、按顺序检查文件是否存在

server {
	
	....
	
    location / {
        root   /usr/share/nginx/html;
        # 如果$uri不存在就请求$uri/,如果再不存在就给交给 http://ip地址:8001 来处理
        try_files $uri $uri/ @java_page;
    }
    
    
    location @java_page{
    	proxy_pass http://ip地址:8001
    }
    
}

7、随机打开一个首页

location / {
    	# 页面首页的路径
        root   /usr/share/nginx/html;
	# on为打开,off为关闭
        random_index on;
        # 首页默认打开的页面
        #index  index.html index.htm;
}

8、内容替换

location / {
    	# 页面首页的路径
        root   /usr/share/nginx/html;
        sub_filter '要替换的内容' '替换后的新内容'
        # off:全局替换,no:单个替换
        sub_filter_once off
        # 首页默认打开的页面
        #index  index.html index.htm;
}

9、请求限制

[root@localhost conf.d]# vim default.conf
	# 连接限制
        limit_conn_zone $binary_remote_addr zone=conn_zone:1m;
        # 每秒只能请求一次
        limit_req_zone $binary_remote_addr zone=req_zone:1m rate=1r/s;
        
server {
	
	......
	
	# 请求限制
	location / {
        root   /usr/share/nginx/html;
        # 同一时刻只允许连接一个
        #limit_conn conn_zone 1;
        # 如果请求超过3个,就放在下一秒执行
        #limit_req conn_zone=req_zone burst=3 nodelay;
        #limit_req conn_zone=req_zone burst=3;
        #limit_req conn_zone=req_zone;
        #index  index.html index.htm;
    }
}

10、访问控制

server {
	
	......
	
	location ~^/admin.html {
        root   /opt/common/admin.html;
        # 禁止该IP访问admin.html
        deny IP地址;
        # 其他的IP都可以访问admin.html
        allow all;
        
        # 只允许该IP访问admin.html
        #allow IP地址;
        # 禁止其他IP访问admin.html
        #deny all;
        
        index  index.html index.htm;
    }
}
server {
	
	......
	
	location / {
		# 如果是以这些数字开头,都不能访问
        if($http_x_forwarded_for !~* "^130\.72\.103") {
        	reutn 403;
        }
        root /opt/html
        index  index.html index.htm;
    }
}

11、压力测试工具:AB

# 安装
[root@localhost /]# yum -y install httpd-tools
# 测试是否安装成功
[root@localhost /]# ab -V
This is ApacheBench, Version 2.3 <$Revision: 1430300 $>
Copyright 1996 Adam Twiss, Zeus Technology Ltd, http://www.zeustech.net/
Licensed to The Apache Software Foundation, http://www.apache.org/
# 测试
# 发出40个请求,并发数为20个, -k:是否开启长连接
[root@localhost /]# ab -n 40 -c 20 http://IP地址/页面.html
This is ApacheBench, Version 2.3 <$Revision: 1430300 $>
Copyright 1996 Adam Twiss, Zeus Technology Ltd, http://www.zeustech.net/
Licensed to The Apache Software Foundation, http://www.apache.org/

Benchmarking 47.107.148.167 (be patient).....done


Server Software:        nginx/1.16.1
Server Hostname:        ************
Server Port:            80

Document Path:          /index.html
Document Length:        612 bytes

Concurrency Level:      20
# 总完成的时间
Time taken for tests:   0.008 seconds
Complete requests:      40
# 请求失败的次数
Failed requests:        0
Write errors:           0
Total transferred:      33800 bytes
HTML transferred:       24480 bytes
# 每秒可以发出5196.83个请求数
Requests per second:    5196.83 [#/sec] (mean)
Time per request:       3.849 [ms] (mean)
Time per request:       0.192 [ms] (mean, across all concurrent requests)
Transfer rate:          4288.40 [Kbytes/sec] received

Connection Times (ms)
              min  mean[+/-sd] median   max
Connect:        0    1   0.2      1       2
Processing:     2    2   0.4      2       3
Waiting:        0    2   0.4      2       3
Total:          2    3   0.5      3       5

Percentage of the requests served within a certain time (ms)
  50%      3
  66%      3
  75%      3
  80%      3
  90%      3
  95%      3
  98%      5
  99%      5
 100%      5 (longest request)

12、内容分发网络:CDN

作用:用来存储静态资源服务

压缩

location ~ .*\.(jpg|gif|png)$ {
	# 开启压缩
        gzip on;
        # 文件压缩版本
        gzip_http_version 1.1;
        # 文件压缩控制的文件大小
        gzip_comp_level 2;
        # 支持的类型
        gzip_types text/plain application/javascript application/x-javascript text/css application/xml text/javascript application/x-httpd-php image-jpeg image/gif image/png;
        root /opt/images;
}

location ~^/download{
	gzip_static on;
	tcp_nopush on;
	root /opt/code;
}

校验是否过期

location ~.*\.(html|vue|jsx)$ {
  expires 24h;
   root /opt/html;
}

允许某个ip地址可以访问或者所有地址都可以访问

location ~.*\.(html|vue|jsx)$ {
	add_header Access-Control-Allow-Origin IP地址|*;
	add_header Access-Control-Allow-Methods GET,POST,PUT,DELETE,OPTIONS;
   	root /opt/html;
}

防盗链

location ~ .*\.(jpg|gif|png)$ {
  	valid_referers none blocked IP地址;
  	if ($invalid_referer) {
 		rewrite ^/ /404.jpg;
      	#return 403;
  	}
}

文件上传

location ^~/upload{
	root /opt/images;
	# 如果是语言php来攻击,就报错403
	if($request_filename~*(.*)\.php){
		return 403;
	}
}

13、负载均衡 | 反向代理

原理:把客户所发出的所有请求通过proxyz_pass配置转发到对应后台的服务器上

events
{
    use epoll;
    worker_connections 65535;
}

http {
	
	# upstream的负载均衡,四种调度算法##
    # 调度算法1:轮询.每个请求按时间顺序逐一分配到不同的后端服务器,如果后端某台服务器宕机,故障系统被自动剔除,使用户访问不受影响
    upstream webhost {
        server 192.168.0.5:6666 ;
        server 192.168.0.7:6666 ;
    }
    # 调度算法2:weight(权重).可以根据机器配置定义权重.权重越高被分配到的几率越大
    upstream webhost {
        server 192.168.0.5:6666 weight=2;
        server 192.168.0.7:6666 weight=3;
    }
    # 调度算法3:ip_hash. 每个请求按访问IP的hash结果分配,这样来自同一个IP的访客固定访问一个后端服务器,有效解决了动态网页存在的session共享问题
    upstream webhost {
        ip_hash;
        server 192.168.0.5:6666 ;
        server 192.168.0.7:6666 ;
    }
    
    
    upstream webhost{
        # down:该端口不提供服务
        server ip地址:端口号 down;
        # downup:该端口为备份服务
        server ip地址:端口号 downup;
        # 允许请求失败次数为1次,经过失败后,服务暂停的时间为10秒
        server ip地址:端口号 max_fails=1  fail_timeout=10s;
        # 限制最大的接受的连接数、最小连接数
        server ip地址:端口号 max_conns = 10  least_conn=10;
        ......
    }
	
	
    # 虚拟主机的配置(采用调度算法3:ip_hash)
    server
    {
        listen 80;
        server_name www.xxx.com;
        # 对 "/" 启用反向代理
        location / {
        	root  /root;  # 定义服务器的默认网站根目录位置
        	
            proxy_pass http://webhost;
            proxy_redirect off;
            proxy_set_header X-Real-IP $remote_addr;
            # 后端的Web服务器可以通过X-Forwarded-For获取用户真实IP
            proxy_set_header X-Forwarded-For $remote_addr;
            # nginx跟后端服务器连接超时时间(代理连接超时)
            proxy_connect_timeout 90;   
            # 后端服务器数据回传时间(代理发送超时)
            proxy_send_timeout 90;     
            # 连接成功后,后端服务器响应时间(代理接收超时)
            proxy_read_timeout 90;    
            # 设置代理服务器(nginx)保存用户头信息的缓冲区大小
            proxy_buffer_size 4k;     
            # proxy_buffers缓冲区,网页平均在32k以下的话,这样设置
            proxy_buffers 4 32k;  
            # 高负荷下缓冲大小(proxy_buffers*2)
            proxy_busy_buffers_size 64k;    
            # 设定缓存文件夹大小,大于这个值,将从upstream服务器传
            proxy_temp_file_write_size 64k;    
            # 允许客户端请求的最大单文件字节数
            client_max_body_size 10m;  
            # 缓冲区代理缓冲用户端请求的最大字节数
            client_body_buffer_size 128k;      
        }
    }
}
# 禁用规则
iptables -I INPUT -p tcp -dport 8001 -j DROP
# 开放规则
iptables -F

14、缓存服务

server{
	.....
	
	proxy_cache_path /opt/app/cache levels=1:2 keys_zone=test_cache:10m max_size=10g inactive=60m use_temp_path=off;
	
	location / {
		proxy_cache test_cache;
		proxy_pass http://test;
		proxy_cache_valid 200 304 12h;
		proxy_cache_valid any 10m;
		proxy_cache_key $host$uri$is_args$args;
		add_header Nginx-Cache "$upstream_cache_status";
		
		proxy_next_upstream error timeout invalid_header http_500 http_502 ...
	}
}

15、限流

# $binary_remote_addr 针对客户端ip限流;
# zone=ip_limit:10m 限流规则名称为ip_limit,允许使用10MB的内存空间来记录ip对应的限流状态
# rate=10r/s 限流速度为每秒10次请求
# location /login/ 对登录进行限流

limit_req_zone $binary_remote_addr zone=ip_limit:10m rate=10r/s;
server {
    location /login/ {
        limit_req zone=ip_limit;
        proxy_pass http://login_upstream;
    }
}

16、动静态分离

pstream java_api{
	server 127.0.0.1:8081
}
server {
    
    ......
    
     # 动态和静态资源都放在这
    root /opt/app/code
	
     location ~\.jsp${
		proxy_pass http://java_api
      }

     location ~ \.(jpg|png|gif)${
		expires 1h;
		gzip on;
      }     
}

17、rewrite规则

rewrite 正则表达式 地址 flag

  • last:停止rewrite检测
  • break:停止rewrite检测
  • redirect ==》返回302临时重定向
  • permanent==》返回301永久重定向
upstream java_api{
	server 127.0.0.1:8081;
}
server {
    
    .....
    
    root /opt/common;
	
	location ~^/break{
		# 以/break开头,就会定位到/test目录下
		rewrite ^/break /test/  break;
	}

	location /test/ {
		default_type application/json;
		return 200 '{"status":"success"}';
	}
	
	
	location / {
		# 判断是否是谷歌浏览器,如果是就重定向
		if($http_user_agent ~* Chrome){
			rewrite ^/nginx ip地址 redirect;
		}
	}
	
	
	location /file {
		# 判断该文件是否存在,如果是就重定向
		if(!-f $request_filename){
			rewrite ^/(.*)$ ip地址 redirect;
		}
	}
	
}

18、secure_link_module

server {
	
	....
    
    root /opt/img;
	
	location / {
		
		secure_link $arg_md5,$arg_expires;
		secure_link_md5 "$secure_link_expires$uri 盐值";
		
		if($secure_link = ""){
			return 403;
		}

		if($secure_link = "0"){
			return 410;
		}
	}
}
yum install openssl
[root@localhost nginx]# vim test.sh

bin/sh
#Auth: qiushanglin
servername="www.xxx.com"
download_file="/opt/common/img/download.jpg"
time_num=$(date -d "2019-11-06 09:26:22" +%s)
secret_num="DSOMAJRAGSKA"

res=$(echo -n "${time_num}${download_file} ${secret_num}"|openssl md5 -binary |openssl base64 | tr +/ -_ | tr -d =)

echo "http://${servername}${download_file}?md5=${res}&expires=${time_num}"
sh test.sh
访问:http://www.xxx.com/opt/common/img?md5=7Rx3WZq1d-1fYs4ZVuKqHQ&expires=1573003582

19、http_geoip_module

安装

yum install nginx-module-geoip

查看

/etc/nginx/modules

使用场景

  • 区别国内外做http访问规则
  • 区别国内城市地域作http访问规则
load_module "ngx_http_geoip_module.so"
load_module "ngx_stream_geoip_module.so"


server {
	......
}

20、SSL

查看是否安装了SSL

[root@localhost ~]# openssl version
OpenSSL 1.0.2k-fips  26 Jan 2017

[root@localhost nginx]# rpm -qa|grep openssl
xmlsec1-openssl-1.2.20-7.el7_4.x86_64
openssl-libs-1.0.2k-19.el7.x86_64
openssl-devel-1.0.2k-19.el7.x86_64
openssl-1.0.2k-19.el7.x86_64

生成SSL秘钥

[root@localhost nginx]# mkdir ssl_key
[root@localhost ssl_key]# openssl genrsa -idea -out jesonc.key 1024
Generating RSA private key, 1024 bit long modulus
...++++++
.....................++++++
e is 65537 (0x10001)
Enter pass phrase for jesonc.key: admin(不会被显示)
Verifying - Enter pass phrase for jesonc.key: admin(不会被显示)

[root@rabbit ssl_key]# openssl req -new -key  jesonc.key -out jesonc.csr
Enter pass phrase for jesonc.key:
You are about to be asked to enter information that will be incorporated
into your certificate request.
What you are about to enter is what is called a Distinguished Name or a DN.
There are quite a few fields but you can leave some blank
For some fields there will be a default value,
If you enter '.', the field will be left blank.
-----
Country Name (2 letter code) [XX]:CN
State or Province Name (full name) []:shenzheng
Locality Name (eg, city) [Default City]:shenzhen 
Organization Name (eg, company) [Default Company Ltd]:test
Organizational Unit Name (eg, section) []:www.xxx.com
Common Name (eg, your name or your server's hostname) []:www.xxx.com
Email Address []:test

Please enter the following 'extra' attributes
to be sent with your certificate request
A challenge password []:
An optional company name []:test
[root@rabbit ssl_key]# ls
jesonc.csr  jesonc.key

# 打包ssl
[root@localhost ssl_key]# openssl req -days 3650 -x509 -sha256 -nodes -newkey rsa:2048 -keyout jesonc.key -out jesonc.cst
Generating a 2048 bit RSA private key
................+++
..................................................................+++
writing new private key to 'jesonc.key'
-----
You are about to be asked to enter information that will be incorporated
into your certificate request.
What you are about to enter is what is called a Distinguished Name or a DN.
There are quite a few fields but you can leave some blank
For some fields there will be a default value,
If you enter '.', the field will be left blank.
-----
Country Name (2 letter code) [XX]:CN
State or Province Name (full name) []:shenzhen
Locality Name (eg, city) [Default City]:shenzhen
Organization Name (eg, company) [Default Company Ltd]:
Organizational Unit Name (eg, section) []:
Common Name (eg, your name or your server's hostname) []:
Email Address []:

配置

server {
    listen       443 ssl;
    server_name  localhost www.xxx.com;
	# 激活长连接
	keypalive_timeout 100;
	
    # 开启ssl
    ssl on;
    # ssl证书文件位置(常见证书文件格式为:crt/pem)
    ssl_certificate      cert.pem;
    # ssl证书key位置
    ssl_certificate_key  cert.key;
    
    # 配置ssl缓存为10兆
    ssl_session_cache  shared:SSL:10m;
    # 配置ssl过期时间
    ssl_session_timeout 10m;
    # 数字签名,此处使用MD5
    ssl_ciphers  HIGH:!aNULL:!MD5;
    ssl_prefer_server_ciphers  on;
    
    ssl_certificate /etc/nginx/ssl_key/jesonc.cst;
    ssl_certificate_key /etc/nginx/ssl_key/jesonc.key;
        
     location / {
        root   页面摆放的地址;
        index  index.html index.htm;
     }

        .......
}
server {
        listen       443 ssl;
        server_name  localhost;

        ssl_certificate      cert.pem;
        ssl_certificate_key  cert.key;

        ssl_session_cache    shared:SSL:1m;
        ssl_session_timeout  5m;

        ssl_ciphers  HIGH:!aNULL:!MD5;
        ssl_prefer_server_ciphers  on;

        location / {
            root   html;
            index  index.html index.htm;
        }
    }

21、静态资源文件配置

worker_processes  1;

events {
    worker_connections  1024;
}

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

    gzip on;
    gzip_types text/plain application/x-javascript text/css application/xml text/javascript application/javascript image/jpeg image/gif image/png;
    gzip_vary on;

    server {
        listen       80;
        server_name  static.zp.cn;

        location / {
            root /app/dist;
            index index.html;
            #转发任何请求到 index.html
        }
    }
}

22、文件句柄

# 打开
vim /etc/security/limits.conf

# 最后加入
root soft nofile 65535
root hard nofile 65535
* 	soft nofile 25535
* 	hard nofile 25535
[root@localhost nginx]# vim nginx.conf

.....

worker_rlimit_nofile 65535;

......

23、跨域

创建一个文件enable-cors.conf,然后在default,conf引入

# allow origin list
set $ACAO '*';

# set single origin
if ($http_origin ~* (www.helloworld.com)$) {
  set $ACAO $http_origin;
}

if ($cors = "trueget") {
    add_header 'Access-Control-Allow-Origin' "$http_origin";
    add_header 'Access-Control-Allow-Credentials' 'true';
    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';
}

if ($request_method = 'OPTIONS') {
  set $cors "${cors}options";
}

if ($request_method = 'GET') {
  set $cors "${cors}get";
}

if ($request_method = 'POST') {
  set $cors "${cors}post";
}
server {
  listen       80;
  server_name  www.helloworld.com;

  location ~ ^/api/ {
    include enable-cors.conf;
    proxy_pass http://api_server;
    rewrite "^/api/(.*)$" /$1 break;
  }
}
  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值