Linux Centos7 實現nginx的代理服務器、七層負載均衡以及動靜分離

一:環境
準備一個nginx代理服務器 三臺http服務器兩臺處理靜態和一臺處理動態。(nginx/1.17.3)php

2、在nginx主配置文件配置nginx反向代理upstream(地址池)指向真實服務器css

vim /etc/nginx/nginx.conf

在http標籤中加html

upstream static {
    server 10.30.161.214:80 weight=2 max_fails=2 fail_timeout=2s;
    server 10.30.161.242:80 weight=2 max_fails=2 fail_timeout=2s;
    }   
    upstream php {
    server 10.30.161.241:80 weight=2 max_fails=2 fail_timeout=2s;   
    }

3、在子配置文件中mysql

vim /etc/nginx/conf.d/proxy.conf

一、動態資源加載
在server標籤中添加nginx

location ~ \.(php|jsp)$ {
    proxy_pass http://phpserver;
    #指向動態服務器地址池
    proxy_set_header Host $host:$server_port;
    #從新定義或者添加發日後端服務器的請求頭$host真實服務器主機名$server_port端口
    proxy_set_header X-Real-IP $remote_addr;
    #啓用客戶端真實地址(不然日誌中顯示的是代理在訪問網站)
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    #顯示http請求端的真實IP
    }

二、靜態資源加載web

location ~ .*\.(html|gif|jpg|png|bmp|swf|css|js)$ {
        proxy_pass http://static;
        proxy_set_header Host $host:$server_port;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
            }
        }

至此代理服務器配置完成sql

4、兩臺靜態服務器的單獨配置vim

server {
    listen 80;
    server_name     localhost;

    location ~ \.(html|jpg|png|js|css|gif|bmp|jpeg) {
    root   /web1;
    index  index.html;
}

}
配置靜態項目
靜態服務器1後端

mkdir /web1
        echo "this is jingtai11111" > /web1/index.html

靜態服務器2瀏覽器

mkdir /web1
        echo "this id jingtai22222" > /web1/index.html

5、一臺動態服務器的單獨配置

yum 安裝php7.1
[root@nginx-server ~]#rpm -Uvh https://mirror.webtatic.com/yum/el7/epel-release.rpm
[root@nginx-server ~]#rpm -Uvh https://mirror.webtatic.com/yum/el7/webtatic-release.rpm
[root@nginx-server ~]#yum install php71w-xsl php71w php71w-ldap php71w-cli php71w-common php71w-devel php71w-gd php71w-pdo php71w-mysql php71w-mbstring php71w-bcmath php71w-mcrypt -y
[root@nginx-server ~]#yum install -y php71w-fpm
[root@nginx-server ~]#systemctl start php-fpm
[root@nginx-server ~]#systemctl enable php-fpm

編輯nginx的配置文件:

server {
        listen      80;
        server_name     localhost;
        location ~ \.php$ {
            root           /web1;  #指定網站目錄
            fastcgi_pass   127.0.0.1:9000;    #指定訪問地址
            fastcgi_index  index.php;       #指定默認文件
            fastcgi_param  SCRIPT_FILENAME  $document_root$fastcgi_script_name; #站點根目錄,取決於root配置項
            include        fastcgi_params;  #包含nginx常量定義
                }
        }

配置動態web1上項目

mkdir /web1
 cd /web1
 vim index.php 
 <?php
phpinfo();
?>

6、測試
1,靜態訪問測試
用瀏覽器訪問代理服務器IP 10.30.161.51/index.html
便可訪問到靜態服務器/web1上的項目,而且兩臺服務器來回切換,這就實現了nginx的代理和負載均衡

2,動態訪問測試用瀏覽器訪問代理服務器IP 10.30.161.51/index.php便可訪問到動態服務器/web1上的項目,從而實現了nginx的動靜分離

相關文章
相關標籤/搜索