nginx基本配置

location匹配模式

模式                  含义
location = /uri = 表示精确匹配,只有完全匹配上才能生效
location ^~ /uri    ^~ 开头对URL路径进行前缀匹配,并且在正则之前。
location ~ pattern  开头表示区分大小写的正则匹配
location ~* pattern 开头表示不区分大小写的正则匹配
location /uri   不带任何修饰符,也表示前缀匹配,但是在正则匹配之后
location /  通用匹配,任何未匹配到其它location的请求都会匹配到,相当于switch中的default

proxy_pass反向代理

##第一种(访问IP转发到IP+端口)
server {
    listen 9003;
    server_name 192.168.50.248;
    index index.php index.html index.htm;
    
    location / {
        proxy_pass http://127.0.0.1:9002;
    }
}
当访问192.168.50.248:9003 的时候, 就会转发到192.168.1.114的9002端口, 9002端口我配置的是PHPinfo(); 所以最终会显示PHPinfo的信息.
##第二种(访问域名转发到IP+端口去)
server{
    listen 80;
    server_name www.test1.com;
    index index.php index.html index.htm;
    
    location /{
        proxy_pass http://127.0.0.1;
    }
}
访问www.test1.com 转发到192.168.50.248默认的nginx显示的页面, 同样可以加上端口比如: http://127.0.0.1:9002; 就跳转到PHPinfo页面
##第三种(访问IP转发到域名)
server {
    listen 9003;
    server_name 192.168.50.248;
    index index.php index.html index.htm;
    
    location /{
        proxy_pass http://www.rubbish.top;
    }
}
##第四种(访问域名转发到域名)
server{
    listen 80;
    server_name www.test1.com;
    index index.php index.html index.htm;
    
    location /{
        proxy_pass http://www.baidu.com;
    }
}
访问www.test1.top跳转到百度.

proxy_pass的http反向代理

proxy_set_header X-Forwarded-Host $host;
proxy_set_header X-Forwarded-Server $host;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header Host $host;
location /api {
    proxy_pass http://192.168.5.250:8081;
    proxy_connect_timeout 600;
    proxy_read_timeout 600;
}
location /{
proxy_pass http://127.0.0.1:8008;   #转发请求
}

proxy_pass http://web_pools;  用于指定反向代理服务器的服务器池。
proxy_set_header  Host  $host;  作用web服务器上有多个站点时,用该参数header来区分反向代理哪个域名。比如下边的代码举例。
proxy_set_header X-Forwarded-For  $remote_addr; 作用是后端服务器上的程序获取访客真实IP,从该header头获取。部分程序需要该功能。

upstream负载均衡

upstream backend {
  ip_hash;
  server   backend1.example.com;
  server   backend2.example.com;
  server   backend3.example.com  down;
  server   backend4.example.com;
}

tcp流量转发

stream {
    upstream cloudsocket {
       hash $remote_addr consistent;
      # $binary_remote_addr;
       server 192.168.107.150:3306 weight=5 max_fails=3 fail_timeout=30s;
    }
    server {
       listen 3307;#数据库服务器监听端口
       proxy_connect_timeout 10s;
       proxy_timeout 300s;#设置客户端和代理服务之间的超时时间,如果5分钟内没操作将自动断开。
       proxy_pass cloudsocket;
    }
}
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

友情链接更多精彩内容