一:環境
準備一個nginx代理服務器 三臺http服務器兩臺處理靜態和一臺處理動態。(nginx/1.17.3)
二、在nginx主配置文件配置nginx反向代理upstream(地址池)指向真實服務器
vim /etc/nginx/nginx.conf
在http標籤中加
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;
}
三、在子配置文件中
vim /etc/nginx/conf.d/proxy.conf
1、動態資源加載
在server標籤中添加
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
}
2、靜態資源加載
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;
}
}
至此代理服務器配置完成
四、兩臺靜態服務器的單獨配置
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
五、一臺動態服務器的單獨配置
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();
?>
六、測試
1,靜態訪問測試
用瀏覽器訪問代理服務器IP 10.30.161.51/index.html
即可訪問到靜態服務器/web1上的項目,並且兩臺服務器來回切換,這就實現了nginx的代理和負載均衡
2,動態訪問測試
用瀏覽器訪問代理服務器IP 10.30.161.51/index.php
即可訪問到動態服務器/web1上的項目,從而實現了nginx的動靜分離