Nginx七大应用场景及配置

时间:2024-03-16 19:23:48

目录

一、Web服务器

​编辑1.HTTP

2.HTTPS

二、反向代理

三、负载均衡

四、重定向

1.老域名跳转新域名 

2.路径重定向 

五、防盗链

 六、手机端重定向PC端

七、基于请求路径转发不同服务


一、Web服务器

1.HTTP

server {
  listen 80;
  server_name _;
  location / {
    root /data;
    index index.html index.htm;  
  }
}

2.HTTPS

server {
  listen 443 ssl;
  server_name _;
  ssl_certificate /path/to/certificete.crt;
  ssl_certificate_key /path/to/private-key.key;
  location / {
    root /data;
    index index.html index.htm;  
  }
}

二、反向代理

server {
  listen 80;
  server_name _;
  location / {
    proxy_pass http://192.168.241.11;
    proxy_set_header Host $host;
    proxy_set_header X-Real-IP $remote_addr;
  }
}

三、负载均衡

upstream web {
  ip_hash
  #会话保持
  server 192.168.241.22;
  server 192.168.241.23;
}
server {
  listen 80;
  server_name _;
  location / {
    proxy_pass http://web;
    proxy_set_header Host $host;
    proxy_set_header X-Real-IP $remote_addr;
  }
}

四、重定向

1.老域名跳转新域名 

server {
  listen 80;
  server_name old.cxk.cn;
  location / {
    rewrite ^/(.*)$ https://new.cxk.cn/$1;
  }
}

2.路径重定向 

server {
  listen 80;
  server_name old.cxk.cn;
  location / {
    rewrite ^/old.cxk.cn/(.*)$ /new-path/$1;
  }
}

五、防盗链

server {
  listen 80;
  server_name _;
  location ~* \.(gif|jpg|jpeg|png) {
    valid_referers none blocked *.cxk.cn;
    if ($invalid_referer) {
      return 403;
    }
  }
}

 六、手机端重定向PC端

server {
  listen 80;
  server_name _;
  location / {
    if ($http_user_agent ~* '(android|iphone|ipad)') {
      return ^/(.*)$ https://yd.cxk.cn/$1;
    }
  }
}

七、基于请求路径转发不同服务

server {
  listen 80;
  server_name _;
  location / {
    proxy_pass http://192.168.241.11;
    proxy_set_header Host $host;
    proxy_set_header X-Real_IP $remote_addr;
  }
  location /beijing {
    proxy_pass http://192.168.241.22;
    proxy_set_header Host $host;
    proxy_set_header X-Real_IP $remote_addr;
  }
  location /nanjing {
    proxy_pass http://192.168.241.23;
    proxy_set_header Host $host;
    proxy_set_header X-Real_IP $remote_addr;
  }
}