nginx由nginx核心和子產品組成,核心的設計非常簡潔,要處理的工作也非常簡單,隻需要通過配置檔案,把用戶端的請求映射到對應的location,然後由location來比對并啟動對應的子產品去完成對應的工作。
- 環境
192.168.2.118 nginx
192.168.2.112 lap/discus
192.168.2.111 lap/discus
- nginx安裝
其中預設安裝需要rewrite子產品,是以要先安裝pcre
yum install pcre-devel pcre -y openssl openssl-devel
useradd www
mkdir nginxtest
cd nginxtest
wget -c http://nginx.org/download/nginx-1.12.0.tar.gz
tar -zxvf nginx-.tar.gz
cd nginx-
./configure --user=www --group=www --prefix=/usr/local/nginx --with-http_stub_status_module --with-http_ssl_module
make
make install
nginx初始目錄
[root@mysqlm nginx]# ls
conf html logs sbin
啟動nginx并檢視啟動狀态
/usr/local/nginx/sbin/nginx
[root@mysqlm sbin]# ps -ef | grep nginx
root : ? :: nginx: master process ./nginx
www : ? :: nginx: worker process
root : pts/ :: grep nginx
[root@mysqlm sbin]# netstat -tunpl | grep 80
tcp ...: ...:* LISTEN /nginx
浏覽器通路nginx頁面
至此nginx安裝完成。
- nginx負載均衡配置
上述安裝完成的nginx配置檔案都是預設值。
在nginx.conf下的http子產品尾部添加
把nginx.conf預設的80端口改成8081(隻要不是80,為了避免沖突)
在conf目錄下添加vhost目錄并添加lee.conf内容如下
upstream web_lee1{
server .: weight= max_fails= fail_timeout=s;
server .: weight= max_fails= fail_timeout=s;
}
server {
listen ;
server_name www.lee1.com;
access_log logs/lee1.access.log;
index index.jsp index.html index.htm;
root /data/webapps/lee1;
location / {
index index.html index.htm;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_pass http://web_lee1;
}
# access_log /usr/local/nginx/logs/lee1/access.log main;
# error_log /usr/local/nginx/logs/lee1/error.log crit;
}
上述的server表示一個虛拟主機,也可以配置多個server,也即多個虛拟域名的主機,此時多個域名對應同一個端口80
可以把upstream放在nginx.conf下,然後把server放在單獨的檔案中以便維護
浏覽器通路192.168.2.118可以看到如下
此時nginx會輪詢通路111和112的apache服務。隻要有111服或112服的apache服務在運作,就可以直接通路。任何其中一個伺服器的apache服務挂了,nginx會自動判斷并直接通路apache服務正常的那台伺服器。
- nginx的動靜分離部署
ngingx可以把用戶端的動态請求和靜态請求分開,nginx處理靜态頁面,而動态頁面由nginx轉到php/jsp/tomcat等後端去處理。
首先進入/usr/local/apache2/htdocs/static/image/common下,把logo.png改成logo.png.bak,此時首頁裡的logo消失
把112的釋出目錄發送到118的/data/webapps/lee1/下
在上面配置檔案nginx.conf中,添加下面内容到server
location ~ .*\.(php|jsp|cgi|shtml)?$
{
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_pass http://web_lee1;
}
location ~ .*\.(gif|jpg|jpeg|bmp|png|ico|txt|js|css)$
{
root /data/webapps/lee1/;
# expires 60d;
}
然後重新加載nginx
/usr/local/nginx/sbin/nginx -s reload
浏覽器輸入網址後可以重新顯示logo圖像,說明此時讀取的是118裡的圖檔