nginx简单负载均衡配置,包括http和https(这里以俩台服务器做演示)

貌似好久没有更新文章了…实在是忙呐 今天就nginx负载转发配置写个简单流程配置,以做记录

俩台服务器为例子

其实https转发也基本和80类似   你每个nginx都需要加ssl证书 转发机nginx监听443端口即可  其他机子没有必要

A服务器 192.168.1.1     做为主转发服务器   同时转发给自己

B服务器 192.168.1.2

A服务器配置如下

#nginx服务器负载模块
upstream  www{
     server 192.168.1.1:8081 weight=10 fail_timeout=60s max_fails=10;
     server 192.168.1.2:8082 weight=10 fail_timeout=60s max_fails=10;
}

server {
    listen 80;           #监听80   也可以443
    server_name xxx.com  #主域名
    root /data/wwwroot/;
    index index.html index.htm index.php;
    #如果监听443需要加证书路径 配置等
    location / {
        proxy_pass http://www/;    #这里注意的是 如果你是https 443端口 一定要写成proxy_pass https://www/;
        proxy_connect_timeout 2s;
        proxy_set_header Host   $host;
    }
}
#处理转发给自己的请求
server {
 listen 8081; 
 server_name 192.168.1.1
 root /data/wwwroot/;
 index index.html index.htm index.php;
 #如果监听443需要加证书路径 配置等
 location / {
    #这里配置省略
 }
}

B服务器配置如下

#处理A服务器转发给自己的请求
server {
 listen 8082; 
 server_name 192.168.1.2
 root /data/wwwroot/;
 index index.html index.htm index.php;
 #如果监听443需要加证书路径 配置等
 location / {
    #这里配置省略
 }
}

这里其实简单的负载就做好了,大家可以在网站目录俩台服务器放不同的内容输出,就可以看到效果啦

nginx服务器301重定向配置

301重定向不陌生, 有时候有需求把某目录整个重定向到一个二级域名,或者不带www的顶级域名请求全部重定向到带www的二级域名.一般这样对seo印象较大。

顶级域名定向到www二级域名

 server {
 listen 80;
 server_name xxxx.com;
 if ($host = 'xxxx.com' ) {
 rewrite ^/(.*)$ http://www.xxxx.com/$1 permanent;
 }

目录跳转新域名

if ( $request_filename ~ nginx/ ) {
 rewrite ^ http://nginx.xxxx.com/? permanent;
 }

 目录重定向

 if ( $request_filename ~ nginxjiaocheng/ ) {
  rewrite ^ http://www.xxxx.com/nginx/? permanent;
 }