章工运维 章工运维
首页
  • linux
  • windows
  • 中间件
  • 监控
  • 网络
  • 存储
  • 安全
  • 防火墙
  • 数据库
  • 系统
  • docker
  • 运维工具
  • other
  • elk
  • K8S
  • ansible
  • Jenkins
  • GitLabCI_CD
  • 随笔
  • 面试
  • 工具
  • 收藏夹
  • Shell
  • python
  • golang
友链
  • 索引

    • 分类
    • 标签
    • 归档
    • 首页 (opens new window)
    • 关于我 (opens new window)
    • 图床 (opens new window)
    • 评论 (opens new window)
    • 导航栏 (opens new window)
周刊
GitHub (opens new window)

章工运维

业精于勤,荒于嬉
首页
  • linux
  • windows
  • 中间件
  • 监控
  • 网络
  • 存储
  • 安全
  • 防火墙
  • 数据库
  • 系统
  • docker
  • 运维工具
  • other
  • elk
  • K8S
  • ansible
  • Jenkins
  • GitLabCI_CD
  • 随笔
  • 面试
  • 工具
  • 收藏夹
  • Shell
  • python
  • golang
友链
  • 索引

    • 分类
    • 标签
    • 归档
    • 首页 (opens new window)
    • 关于我 (opens new window)
    • 图床 (opens new window)
    • 评论 (opens new window)
    • 导航栏 (opens new window)
周刊
GitHub (opens new window)
  • linux

  • windows

  • 中间件

    • nginx

      • nginx配置教程
      • nginx常用配置
        • 虚拟主机
        • nginx负载均衡
        • 反向代理
          • 代理oss
        • location规则
        • 证书
        • 日志
        • php配置
        • 模块
        • 跳转、重定向
        • 虚拟目录
        • nginx跨域
        • php配置
        • 防止域名恶意解析
        • 网站置灰
      • keepalived的原理和web服务高可用实践
      • 在CentOS 7上编译安装Nginx
      • nginx配置下载站点
      • nginx配置代理ftp
      • nginx配置php程序负载均衡
      • nginx反代grpc
    • kafka

    • rabbitmq

    • centos7.9部署keepalived
    • 应用性能监控-skywalking
  • 网络

  • 安全

  • 存储

  • 防火墙

  • 数据库

  • 系统

  • docker

  • other

  • 监控

  • 运维
  • 中间件
  • nginx
章工运维
2023-02-09
目录

nginx常用配置

# 虚拟主机

虚拟主机的三种方式:基于端口、IP地址、域名

server {

​ listen 80;

​ server_name www.accp.com (opens new window);

​ charset utf-8;

​ access_log logs/www.accp.com.access.log (opens new window);

​ location / {

​ root /var/www/html/accp;

​ index index.html index.htm;

​ }

​ error_page 500 502 503 504 /50x.html;

​ location = /50x.html {

​ root html;

​ }

}

# nginx负载均衡

upstream cluster {

ip_hash; #如果你的系统中没有使用第三方缓存管理工具 ,建议使用此方式

server 192.168.1.210:80 weight=5;

server 192.168.1.211:80 weight=3;

server 192.168.1.212:80 weight=1;

}

upstream dxTreasureIsland_http { server dal05iis39.sl.dx weight=40 max_fails=3 fail_timeout=60s; server iis01.zl.dx:8093 weight=10 max_fails=3 fail_timeout=60s; }

# 反向代理

​ location / {
​ proxy_pass http://localhost:8000/;
​ proxy_redirect off;
​ proxy_set_header Host $http_host;
​ proxy_set_header X-Real-IP $remote_addr;
​ proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
​ location / {
​ proxy_pass http://172.18.184.130:10085;
​ proxy_set_header Host $host;
​ proxy_set_header X-Real-IP $remote_addr;
​ proxy_redirect http:// $scheme://; #以上指令会将后端响应header location内容中的http://替换成用户端协议https://
​ proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;

​ }

location / {

proxy_pass http://baidunode;

proxy_set_header X-Forwarded-Proto $scheme;
proxy_set_header Host $host; #HTTP header 中的 Host 含义为所请求的目的主机名。当 nginx 作为反向代理使用,而后端真实 web 服务器设置有类似 防盗链功能

proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; #HTTP header 中的 X_Forward_For 表示该条 http 请求是由谁发起的

proxy_set_header X-Real-IP $remote_addr;
 proxy_redirect off;

}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28

常用的代理

    location / {
        proxy_pass         http://localhost:8000/;
        proxy_set_header   Host             $http_host;
        proxy_set_header   X-Real-IP        $remote_addr;
        proxy_set_header   X-Forwarded-For  $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
    }
1
2
3
4
5
6
7

proxy_redirect的作用

proxy_redirect 该指令用来修改被代理服务器返回的响应头中的Location头域和“refresh”头域。

  1. proxy_redirect 旧地址 新地址;

  2. proxy_redirect default; #默认配置

  3. proxy_redirect off; #关闭重定向

# 代理oss

server {
 listen 443 ssl;
 server_name test.xxxxxx.com;
 ssl on;
 ssl_certificate /cert/xxxxxx.com/9298143__xxxxxx.com.pem;
 ssl_certificate_key /cert/xxxxxx.com/9298143__xxxxxx.com.key;
 ssl_ciphers ECDHE-RSA-AES128-GCM-SHA256:ECDHE:ECDH:AES:HIGH:!NULL:!aNULL:!MD5:!ADH:!RC4;
 ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
 ssl_prefer_server_ciphers on;
 location / {
 proxy_set_header Host test.xxxxxx.com;
 proxy_pass https://test.xxxxxx.com;
 proxy_hide_header Content-Disposition;
 add_header Content-Disposition 'inline';

 }
}
这里我们使用了 proxy_hide_header Content-Disposition; 来删除从 OSS 接收到的原始 Content-Disposition 头,然后用 add_header Content-Disposition 'inline'; 添加新的 Content-Disposition 头。将其值设置为 inline 可以让浏览器尝试在线查看文件(如果支持的话)而不是下载它们。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18

# location规则

配置location /wandou可以匹配/wandoudouduo请求,也可以匹配/wandou*/duoduo等等,只要以wandou开头的目录都可以匹配到。而location /wandou/必须精确匹配/wandou/这个目录的请求,不能匹配/wandouduoduo/或/wandou*/duoduo等请求。

第一种:加"/"
location /wddd/ {
 proxy_pass [http://127.0.0.1:8080/](http://127.0.0.1:8080/);
}
测试结果,请求被代理跳转到:http://127.0.0.1:8080/index.html 
第二种: 不加"/"
location /wddd/ {  
proxy_pass [http://127.0.0.1:8080](http://127.0.0.1:8080);
}
测试结果,请求被代理跳转到:http://127.0.0.1:8080/wddd/index.html 
第三种: 增加目录加"/"
location /wddd/ {  
proxy_pass http://127.0.0.1:8080/sun/;
}
测试结果,请求被代理跳转到:http://127.0.0.1:8080/sun/index.html 
第四种:增加目录不加"/"
location /wddd/ {
 proxy_pass http://127.0.0.1:8080/sun;
}
测试结果,请求被代理跳转到:http://127.0.0.1:8080/sun/index.html 总结
location目录后加"/",只能匹配目录,不加“/”不仅可以匹配目录还对目录进行模糊匹配。而proxy_pass无论加不加“/”,代理跳转地址都直接拼接
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
符号 说明
~ 正则匹配,区分大小写
~* 正则匹配,不区分大小写
^~ 普通字符匹配,如果该选项匹配,则,只匹配改选项,不再向下匹配其他选项
= 普通字符匹配,精确匹配
@ 定义一个命名的 location,用于内部定向,例如 error_page,try_files

符号@使用例子

server {
    listen 80;
    client_max_body_size 100M;
    keepalive_timeout 5;
    root /app/static;
    location /backend {
    rewrite ^/backend/(.*) /$1 break;
    try_files $uri @proxy_to_app;
    }
    location / {
    try_files $uri @proxy_to_app;
    }
    location @proxy_to_spp {
        proxy_set_header X-Forwarded-Proto $scheme;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header Host $http_host;
        proxy_set_header   X-Real-IP        $remote_addr;
        proxy_redirect off;
        proxy_pass http://app_server;
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21

nginx禁止、允许访问某些后缀的文件 location ~* .(ini|cfg|dwt|lbi)$ {
deny all;
}

# 证书

​ ssl_certificate /etc/ssl/private/.crt; ​ ssl_certificate_key /etc/ssl/private/.key; ​ ssl_session_timeout 5m; ​ ssl_protocols TLSv1 TLSv1.1 TLSv1.2; ​ ssl_ciphers HIGH:!ADH:!aNULL:!eNULL:!MD5:!DSS:!DH:!RC4; ​ ssl_prefer_server_ciphers on;

server {
    listen 443;
    listen 80;
    server_name m.xxx.com;
    ssl on;
    ssl_certificate      /etc/nginx/cert/m.xxx.com/m.goldmanfutures.com_chain.crt;
    ssl_certificate_key  /etc/nginx/cert/m.xxx.com/m.goldmanfutures.com_key.key;
    proxy_ssl_session_reuse   off;
    ssl_session_cache         shared:SSL:1m;
    ssl_session_timeout       5m;
    ssl_ciphers               ECDHE-RSA-AES128-GCM-SHA256:ECDHE:ECDH:AES:HIGH:!NULL:!aNULL:!MD5:!ADH:!RC4;
    ssl_protocols             TLSv1 TLSv1.1 TLSv1.2;
    ssl_prefer_server_ciphers on;
    client_max_body_size 1g;
    client_body_buffer_size 1m;
        if ($scheme = http) {
                rewrite ^(.*)$ https://m.xxx.com$1 permanent;
        }


    index   index.html index.htm index.php;
    location / {
        proxy_pass   http://172.31.186.20:10584/;
        proxy_set_header Host      $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-Proto $scheme;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29

# 日志

​ access_log /var/log/nginx/jenkins.dx.com.access.log;
​ error_log /var/log/nginx/jenkins.dx.com.errors.log;
​

log_format main '$remote_addr - $remote_user [$time_local] "$request" '
 '$status $body_bytes_sent "$http_referer" '
 '"$http_user_agent" "$http_x_forwarded_for"';
1
2
3
4
5
6
7

# php配置

​ location ~ \.php$ {
​ root /data/erp5/website/erp5.pdvee.com/public;
​ index index.php;
​ fastcgi_pass 192.168.14.20:9005;
​ fastcgi_index index.php;
​ fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
​ include fastcgi_params;
​ }
1
2
3
4
5
6
7
8

# 模块

concat模块:Nginx concat通过合并静态文件来减少http请求数来达到优化前端性能,可以在一定程度上能减少web服务器的压力。

location / {
 concat on;
 concat_max_files 100;
 concat_unique off;
 concat_ignore_file_error on;
 if (!-e $request_filename) {
 rewrite ^(.*)$ /index.php?s=/$1 last;
 break;
 }
1
2
3
4
5
6
7
8
9

# 跳转、重定向

​ if ($host ~ ^www\.dealextreme.com\.com$) {
​ rewrite ^(.*)$ $scheme://www.dx.com permanent;
​ }
if ($scheme = http) {
            rewrite ^(.*)$ https://www.dx.com$1 permanent;
    }
1
2
3
4
5
6

server { listen 80; server_name www.zzppjj.top (opens new window) zzppjj.top;

    location ~* / {
            rewrite ^(.*)$ https://www.zzppjj.top$1 permanent;
    }
1
2
3

}

server {
    listen 80;
    server_name getpro-h5-business.goingf.hk getpro-php-business.goingf.hk;



    location / {
        rewrite ^ https://$http_host$request_uri? permanent;    # force redirect http to https
        return 301 https://$http_host$request_uri;
    }

}
1
2
3
4
5
6
7
8
9
10
11
12

重定向到另外一台服务器示例:(查找目录下是否存在文件,如果不存在转到@new_uploads下,new_uploads对应代理到172.17.0.101上)

location ^~ /uploads/ { root /data/weiwend/weiwang; try_files $uri @new_uploads; }

location @new_uploads {
    proxy_redirect off;
    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://172.17.0.101:80;
}
1
2
3
4
5
6
7
  • 将 /api/v1/game/data?id= 新网站路径地址映射到 http://gameid.escape.com/api/v1/new_game/ 老网站的 API 上面,给开发提供获取游戏用户信息的接口

server { listen 80; server_name gameid.escape.com;

access_log /var/log/nginx/gameid.nginx.access.log  netdata;
error_log  /var/log/nginx/gameid.nginx.error.log   error;

location / {
    return 404;
}

location /api/v1/ {
    proxy_pass_header Server;
    proxy_set_header Host $http_host;
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header X-Scheme $scheme;
    proxy_http_version 1.1;
    if ($request_uri ~* "/api/v1/game/data\?id=(.*)") {
        set $id $1;
        rewrite .* /api/v1/new_game/$id break;
        proxy_pass http://gameid.escape.com;
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19

}

# 虚拟目录

​ location /media { ​ alias /usr/share/nginx/html/media;
​ }

# nginx跨域

     #是否允许请求带有验证信息
     add_header Access-Control-Allow-Credentials true;
     #允许跨域访问的域名,可以是一个域的列表,也可以是通配符*
     add_header Access-Control-Allow-Origin  $allow_url;
     #允许脚本访问的返回头
     add_header Access-Control-Allow-Headers 'x-requested-with,content-type,Cache-Control,Pragma,Date,x-timestamp';
     #允许使用的请求方法,以逗号隔开
     add_header Access-Control-Allow-Methods 'POST,GET,OPTIONS,PUT,DELETE';
     #允许自定义的头部,以逗号隔开,大小写不敏感
     add_header Access-Control-Expose-Headers 'WWW-Authenticate,Server-Authorization';
     #P3P支持跨域cookie操作
     add_header P3P 'policyref="/w3c/p3p.xml", CP="NOI DSP PSAa OUR BUS IND ONL UNI COM NAV INT LOC"';
     add_header test  1;
1
2
3
4
5
6
7
8
9
10
11
12
13

需求为浏览器访问B的时候要直接显示A的主页,这样对A做一个代理,浏览器的URL还是B并不是重定向到A。

在A的nginx中加入一下内容

location /api/ {

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 'Origin, X-Requested-With, Content-Type, Accept';

proxy_pass http://gateway_proxy/ (opens new window);

# php配置

server {
        listen 80;
        listen 8888;

        server_name  api.erp.pdvee.com;

        access_log /var/log/nginx/api.erp.pdvee.com.access.log site_log2;
        error_log  /var/log/nginx/api.erp.pdvee.com.errors.log;

        proxy_set_header Host $host;
        proxy_set_header Real-IP $remote_addr;
        proxy_set_header Region $geoip_country_code;
        proxy_set_header X-Forwarded-For $remote_addr;

        root /data/erp/website/erp.pdvee.com;
        index index.php index.html index.htm;


      keepalive_timeout 18000s;
        client_body_timeout 18000s;
        client_header_timeout 18000s;
        proxy_connect_timeout 18000s;
        proxy_send_timeout 18000s;
        proxy_read_timeout 18000s;


    fastcgi_connect_timeout 18000;
    fastcgi_send_timeout 18000;
    fastcgi_read_timeout 18000;
    fastcgi_buffer_size 256k;
    fastcgi_buffers 8 256k;
    fastcgi_busy_buffers_size 256k;
    fastcgi_temp_file_write_size 256k;
    ##
    client_max_body_size 2048m;        
    client_body_buffer_size 256k;




        location / {
#        proxy_cache my_cache;
#        proxy_cache_revalidate on;
                concat on;
                concat_max_files 100;
                concat_unique off;
#                concat_ignore_file_error on;
            if (!-e $request_filename) {
            rewrite ^(.*)$ /index.php?s=/$1 last;
            break;
           }

        }

        location ~ \.php$ {
            root /data/website/erp.pdvee.com;
            index index.php;
            fastcgi_pass   192.168.14.13:9001;
            fastcgi_index  index.php;
            fastcgi_param  SCRIPT_FILENAME  $document_root$fastcgi_script_name;
            include        fastcgi_params;
        }

}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64

全局变量

$bytes_sent             发送给客户端的字节数
$connection             连接序列号
$connection_requests    当前通过连接发出的请求数量
$content_length         “Content-Length” 请求头字段
$content_type           “Content-Type” 请求头字段
$cookie_name            cookie名称
$document_root          当前请求的文档根目录或别名
$uri                    请求中的当前URI(不带请求参数,参数位于$args),可以不同于浏览器传递的$request_uri的值,它可以通过内部重定向,或者使用index指令进行修改,$uri不包含主机名,如”/foo/bar.html”。
$document_uri           同 $uri
$host                   优先级如下:HTTP请求行的主机名>”HOST”请求头字段>符合请求的服务器名
$hostname               主机名
$http_name              匹配任意请求头字段; 变量名中的后半部分“name”可以替换成任意请求头字段,如在配置文件中需要获取http请求头:“Accept-Language”,那么将“-”替换为下划线,大写字母替换为小写,形如:$http_accept_language即可。
$https                  如果开启了SSL安全模式,值为“on”,否则为空字符串。
$is_args                如果请求中有参数,值为“?”,否则为空字符串。
$limit_rate             用于设置响应的速度限制
$nginx_version          nginx版本
$pid                    工作进程的PID
$pipe                   如果请求来自管道通信,值为“p”,否则为“.” (1.3.12, 1.2.7)
$proxy_protocol_addr    获取代理访问服务器的客户端地址,如果是直接访问,该值为空字符串。
$realpath_root          当前请求的文档根目录或别名的真实路径,会将所有符号连接转换为真实路径。
$msec                   以秒为单位的时间,日志写入时的毫秒分辨率
$request_length         请求长度(包括请求行,标题和请求主体)
$request_method         HTTP请求方法,通常为“GET”或“POST”
$request_time           处理客户端请求使用的时间;从读取客户端的第一个字节开始计时。
$request_uri            这个变量等于包含一些客户端请求参数的原始URI,它无法修改,请查看$uri更改或重写URI,不包含主机名,例如:”/cnphp/test.php?arg=freemouse”。
$request_time           以毫秒分辨率请求处理时间,以秒为单位; 从客户端读取第一个字节之间的时间并在最后一个字节发送到客户端后进行日志写入
$status                 响应状态码
$time_local             本地时间采用通用日志格式
$arg_name               请求中的的参数名,即“?”后面的arg_name=arg_value形式的arg_name
$args                   请求中的参数值
$binary_remote_addr     客户端地址的二进制形式, 固定长度为4个字节
$body_bytes_sent        传输给客户端的字节数,响应头不计算在内;这个变量和Apache的mod_log_config模块中的“%B”参数保持兼容
$remote_addr            客户端地址
$remote_port            客户端端口
$remote_user            用于HTTP基础认证服务的用户名
$request                客户端请求地址
$request_body           客户端的请求主体,此变量可在location中使用,将请求主体通过proxy_pass, fastcgi_pass, uwsgi_pass, 和 scgi_pass传递给下一级的代理服务器。
$request_body_file      将客户端请求主体保存在临时文件中。文件处理结束后,此文件需删除。如果需要之一开启此功能,需要设置client_body_in_file_only。如果将次文件传递给后端的代理服务器,需要禁用request body,即设置proxy_pass_request_body off,fastcgi_pass_request_body off, uwsgi_pass_request_body off, or scgi_pass_request_body off 。
$request_completion     如果请求成功,值为”OK”,如果请求未完成或者请求不是一个范围请求的最后一部分,则为空。
$request_filename       当前连接请求的文件路径,由root或alias指令与URI请求生成。
$scheme                 请求使用的Web协议, “http” 或 “https”
$sent_http_name         可以设置任意http响应头字段; 变量名中的后半部分“name”可以替换成任意响应头字段,如需要设置响应头Content-length,那么将“-”替换为下划线,大写字母替换为小写,形如:$sent_http_content_length 4096即可。
$server_addr            服务器端地址,需要注意的是:为了避免访问linux系统内核,应将ip地址提前设置在配置文件中。
$server_name            服务器名,域名
$server_port            服务器端口
$server_protocol        服务器的HTTP版本, 通常为 “HTTP/1.0” 或 “HTTP/1.1”
$tcpinfo_rtt, $tcpinfo_rttvar, $tcpinfo_snd_cwnd, $tcpinfo_rcv_space 客户端TCP连接的具体信息
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47

############

nginx中$host、$http_host和$proxy_host区别
$host    不显示端口       浏览器请求的ip,不显示端口
$http_host 端口存在则显示        浏览器请求的ip和端口号
$proxy_host    默认80端口不显示,其它显示    被代理服务的ip和端口号
1
2
3
4

# 防止域名恶意解析

server {

listen 80 default_server;

server_name _;

return 404;

}

server { listen 443 default_server; server_name _; ssl on; return 444; }

大概解释如下:

default_server:默认域名配置,如果找不到,会自动匹配

server_name _: 无效域名匹配

return 444: 非标准状态码,是Nginx服务器扩展的Http错误状态码,服务器不向客户端返回任何信息,并关闭连接, 断开客户端和服务器的连接,防止恶意软件攻击威胁

三、配置上面到主配置文件后。

重启动nginx ,就会为我们屏蔽恶意访问了。

# 网站置灰

sub_filter  '</head>'  '<style type="text/css">html {-webkit-filter: grayscale(.95);}</style></head>';
    sub_filter_once on; 
1
2
微信 支付宝
上次更新: 2025/02/18, 09:32:44

← nginx配置教程 keepalived的原理和web服务高可用实践→

最近更新
01
shell脚本模块集合
05-13
02
生活小技巧(认知版)
04-29
03
生活小技巧(防骗版)
04-29
更多文章>
Theme by Vdoing | Copyright © 2019-2025 | 点击查看十年之约 | 鄂ICP备2024072800号
  • 跟随系统
  • 浅色模式
  • 深色模式
  • 阅读模式