Nginx web服務(wù)器使用
nginx Linux 安裝
-
安裝依賴
yum -y install gcc zlib zlib-devel pcre-devel openssl openssl-devel -
下載并解壓安裝包
# 在/usr/local/src 創(chuàng)建nginx文件夾 cd /usr/local/src/nginx # 下載tar包 wget http://nginx.org/download/nginx-1.17.3.tar.gz tar -xf nginx-1.17.3.tar.gz 執(zhí)行 ./configure --prefix=/usr/local/nginx (其中 --prefix是指定nginx 安裝路徑 也就是最后安裝到哪)
執(zhí)行 make
執(zhí)行 make install
nginx 相關(guān)命令
/usr/local/nginx/sbin/nginx -s reload # 重新載入配置文件
/usr/local/nginx/sbin/nginx -s reopen # 重啟 Nginx
/usr/local/nginx/sbin/nginx -s stop # 停止 Nginx
nginx 配置文件 /conf/nginx.conf
#user nobody; # 配置worker進(jìn)程運(yùn)行用戶 默認(rèn)為任何用戶都可以
worker_processes 1; #配置工作進(jìn)程數(shù)目,根據(jù)硬件調(diào)整,通常等于CPU數(shù)量或2倍與CPU數(shù)量
#error_log logs/error.log; # 配置全局錯(cuò)誤日志及類型 [debug|info|notice|warn|error|crit] 默認(rèn)為error
#error_log logs/error.log notice;
#error_log logs/error.log info;
#pid logs/nginx.pid; # 配置進(jìn)程編號(hào) pid文件
# 配置工作模式和連接數(shù)
events {
# 配置事件模型
# use epoll;
# 配置每個(gè)worker進(jìn)程連接數(shù)上限,nginx支持的總連接數(shù)就等于worker_processes * worker_connections
worker_connections 1024; # 最大可寫55535
}
# 配置http服務(wù)器,利用他的反向代理功能提供負(fù)載均衡支持
http {
include mime.types; # 配置nginx支持哪些多媒體類型,可以在cong/mime.types中查看支持的多媒體類型
default_type application/octet-stream; # 默認(rèn)文件流類型(一般支持大多數(shù)文件)
# 配置日志格式
#log_format main '$remote_addr - $remote_user [$time_local] "$request" '
# '$status $body_bytes_sent "$http_referer" '
# '"$http_user_agent" "$http_x_forwarded_for"';
# 配置access.log日志及存放路徑,并使用上面定義的main日志格式
#access_log logs/access.log main;
sendfile on; # 開啟搞高效文件傳輸模式
#tcp_nopush on; # 防止網(wǎng)絡(luò)阻塞 在sendfile 開啟后使用
#keepalive_timeout 0;
keepalive_timeout 65; # 連接時(shí)長(zhǎng) 超時(shí)顯示連接失敗
#tcp_nodelay on; # 實(shí)時(shí)發(fā)送不進(jìn)行等待 在keepalive開啟后使用,提供網(wǎng)絡(luò)包的傳輸實(shí)時(shí)性
#gzip on; # 開啟gzip 壓縮輸出
# 配置虛擬主機(jī)
server {
listen 80; # 配置監(jiān)聽端口
server_name localhost; # 配置服務(wù)名
#charset koi8-r; # 配置字符集 通用UTF-8
#access_log logs/host.access.log main; #配置本虛擬主機(jī)的訪問日志
# 默認(rèn) / 請(qǐng)求,當(dāng)訪問路徑中出現(xiàn) / 會(huì)被該location匹配到 并進(jìn)行處理
# 類似于路由的概念 / 路徑為默認(rèn)路徑
location / { # location 用于匹配路由
root html; # root 時(shí)配置服務(wù)器的默認(rèn)網(wǎng)站根目錄位置,默認(rèn)為nginx安裝目錄下的html目錄
index index.html index.htm; # 在html目錄下查找index.html 配置首頁(yè)文件的名稱
}
#error_page 404 /404.html; # 配置 404 頁(yè)面
# redirect server error pages to the static page /50x.html #配置50x 頁(yè)面
#
error_page 500 502 503 504 /50x.html;
location = /50x.html { # location = /50x.html 表示 精確匹配
root html; # 去html 目錄下查看 50x.html
}
# PHP腳本請(qǐng)求全部轉(zhuǎn)發(fā)到Apache 處理
# proxy the PHP scripts to Apache listening on 127.0.0.1:80
#
#location ~ \.php$ {
# proxy_pass http://127.0.0.1;
#}
# PHP腳本請(qǐng)求全部轉(zhuǎn)發(fā)到FastCGI處理
# pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
#
#location ~ \.php$ {
# root html;
# fastcgi_pass 127.0.0.1:9000;
# fastcgi_index index.php;
# fastcgi_param SCRIPT_FILENAME /scripts$fastcgi_script_name;
# include fastcgi_params;
#}
# 禁止訪問 .htaccess文件 防止外網(wǎng)訪問的文件
# deny access to .htaccess files, if Apache's document root
# concurs with nginx's one
#
#location ~ /\.ht {
# deny all;
#}
}
# 另一個(gè)混合使用基于IP、名稱和端口的配置的虛擬主機(jī)
# another virtual host using mix of IP-, name-, and port-based configuration
#
#server {
# listen 8000;
# listen somename:8080;
# server_name somename alias another.alias;
# location / {
# root html;
# index index.html index.htm;
# }
#}
# 配置HTTPS 服務(wù)
# HTTPS server
#
#server {
# listen 443 ssl;
# server_name localhost;
# ssl_certificate cert.pem; # 證書
# ssl_certificate_key cert.key; # 證書公鑰
# ssl_session_cache shared:SSL:1m;
# ssl_session_timeout 5m;
# ssl_ciphers HIGH:!aNULL:!MD5;
# ssl_prefer_server_ciphers on;
# location / {
# root html;
# index index.html index.htm;
# }
#}
}
nginx的主要應(yīng)用
靜態(tài)網(wǎng)站
server{
listen 80;# 端口號(hào)
# ip + port = root root也就是項(xiàng)目文件所在目錄
location /{
root /opt/www/ # 靜態(tài)文件路徑
index index.html # 靜態(tài)文件
}
}
server {
listen 8080; # 配置監(jiān)聽端口
server_name localhost; # 配置服務(wù)名
#charset koi8-r; # 配置字符集 通用UTF-8
#access_log logs/host.access.log main; #配置本虛擬主機(jī)的訪問日志
# 配置路由 www文件夾與nginx.exe 同級(jí)目錄
location / { # location 用于匹配路由
root www; # root 時(shí)配置服務(wù)器的默認(rèn)網(wǎng)站根目錄位置,默認(rèn)為nginx安裝目錄下的html目錄
index index.html index.htm; # 在html目錄下查找index.html 配置首頁(yè)文件的名稱
}
# 配置404 頁(yè)面
error_page 404 /404.html; # 配置 404 頁(yè)面
location = /404.html {
root www;
}
# 配置50x 頁(yè)面
error_page 500 502 503 504 /50x.html;
location = /50x.html { # location = /50x.html 表示 精確匹配
root www; # 去html 目錄下查看 50x.html
}
}
負(fù)載均衡
-
負(fù)載均衡概述
網(wǎng)站創(chuàng)立初期,我們一般都使用單臺(tái)及其對(duì)外提供集中式服務(wù),但隨著業(yè)務(wù)量的正大,我們一臺(tái)服務(wù)器不夠用,此時(shí)就會(huì)把多臺(tái)服務(wù)器組成一個(gè)集群對(duì)外提供服務(wù);但是,我們網(wǎng)站對(duì)外提供的訪問入口通常只有一個(gè),比如www.xxx.com;那么當(dāng)用戶訪問 www.xxx.com的時(shí)候,如何將用戶的請(qǐng)求分發(fā)到集群中不同的機(jī)器上呢,這就是負(fù)載均衡要做的事情;負(fù)載均衡通常是指將請(qǐng)求“均勻”分?jǐn)偟郊褐卸鄠€(gè)服務(wù)器節(jié)點(diǎn)上執(zhí)行,這里的均勻是指在一個(gè)較大的統(tǒng)計(jì)范圍內(nèi)是基本均勻的,并不是完全均勻
-
負(fù)載均衡實(shí)現(xiàn)方式:
- 硬件的負(fù)載均衡
- 比如F5、深信服、Array等;優(yōu)點(diǎn)是有廠商專業(yè)的技術(shù)服務(wù)團(tuán)隊(duì)提供支持;性能穩(wěn)定;缺點(diǎn)是費(fèi)用昂貴,對(duì)應(yīng)規(guī)模較小的網(wǎng)絡(luò)應(yīng)用成本高
- 軟件的負(fù)載均衡
- 比如 Nginx、LVS、HAProxy等;免費(fèi)開源,成本低廉
- 硬件的負(fù)載均衡
-
Nginx 實(shí)現(xiàn)負(fù)載均衡
-
Nginx實(shí)現(xiàn)負(fù)載均衡:通過在Nginx的nginx.conf中 進(jìn)行配置即可
image -
配置如下
- 在http模塊中加入:
upstream test { server 127.0.0.1:8000 weight=3; server 127.0.0.1:8001 weight=1; }其中 weight 表示權(quán)重,用于后端服務(wù)器性能不均的情況,訪問比率約等于權(quán)重之比,權(quán)重越大訪問的機(jī)會(huì)越大;
upstream 是配置nginx與后端服務(wù)器負(fù)載均衡非常重要的一個(gè)模塊,并且它還能對(duì)后端的服務(wù)器的健康狀態(tài)進(jìn)行檢查,若后端服務(wù)器中一臺(tái)發(fā)生故障,則客戶端的請(qǐng)求不會(huì)轉(zhuǎn)發(fā)到該故障機(jī)器
- 在server模塊中添加:
location / { # 訪問項(xiàng)目某個(gè)路徑時(shí) # 代理轉(zhuǎn)發(fā)的地址 域名或地址和端口 proxy_pass http://test; # http:// 必須存在 }其中l(wèi)ocation中 的www.xxx.com字符串要和 upstream 后面的字符串相同
image -
-
負(fù)載均衡常用策略
-
輪詢(默認(rèn)):
每個(gè)請(qǐng)求輪流分配到不同的后端服務(wù)器,如果后端服務(wù)器掛掉或假死,將自動(dòng)剔除,不在進(jìn)行分配;
upstream demo{ server 127.0.0.1:8000; server 127.0.0.1:8001; } -
權(quán)重
每個(gè)請(qǐng)求按比例分發(fā)到不同的后端服務(wù)器,weight的值越大,訪問的幾率越大,用于后端服務(wù)器性能不均
upstream demo{ server 127.0.0.1:8000 weight=2; server 127.0.0.1:8001 weight=2; } -
ip_hash
ip_hash也叫IP綁定,每個(gè)請(qǐng)求按照ip的hash值分配,這樣每個(gè)訪問客戶端會(huì)固定訪問一個(gè)后端服務(wù)器,可以解決session會(huì)話丟失問題
# 通過hash("ip")%服務(wù)器的臺(tái)數(shù) = 結(jié)果匹配到對(duì)應(yīng)的ip # hash('183.199.76.201')% 2 = 1 因此會(huì)匹配到 127.0.0.1:8001 upstream demo{ ip_hash; server 127.0.0.1:8000; server 127.0.0.1:8001; } -
最少連接
web請(qǐng)求會(huì)轉(zhuǎn)發(fā)到連接數(shù)最少的服務(wù)器上
upstream demo{ least_conn; server 127.0.0.1:8000; server 127.0.0.1:8001; } -
其他配置
-
backup(預(yù)備機(jī)器) 其他所有的非backup機(jī)器down的時(shí)候,才請(qǐng)求backup機(jī)器
upstream demo{ server 127.0.0.1:8000; server 127.0.0.1:8001 backup; } -
down(停止機(jī)器) 當(dāng)前的server為down狀態(tài),不參與負(fù)載均衡
upstream demo{ server 127.0.0.1:8000; server 127.0.0.1:8001 down; }
-
-
靜態(tài)代理
把所有的靜態(tài)資源的訪問改為訪問nginx,而不是再去訪問tomact ,因?yàn)閚ginx更擅長(zhǎng)與靜態(tài)資源的處理,性能更好,效率更高
所有在實(shí)際應(yīng)用中,我們將靜態(tài)資源比如圖片、css、html、js等交割給nginx 處理,而不是由tomcat處理;
通過在nginx.conf 配置文件中添加靜態(tài)資源的文件名
放置靜態(tài)資源的目錄,要注意目錄權(quán)限的問題
location ~ .*\.(js|css|html|htm|gif|png|jpg|jpeg|bmp|swf|icon|rar|zip|txt|flv|mid|doc|ppt|pdf|xls|mp3|mp4|wma)$ {
root static;
}
# 當(dāng) 訪問頁(yè)面圖片為 /src/img/001.jpg
# 那么 是訪問的 static/src/img/001.jpg
通過在nginx.conf配置文件中配置靜態(tài)資源所在目錄實(shí)現(xiàn)
location ~ .*/(css|img|js|images){
root static
}
# 當(dāng) 訪問頁(yè)面圖片為 demo/img/001.jpg
# 那么 nginx可以匹配到 img 就會(huì)去static/img中尋找001.jpg
我們將靜態(tài)資源放入 /static 目錄下,然后用戶訪問時(shí)由nginx 返回這些靜態(tài)資源
配置如下
// 創(chuàng)建一個(gè)服務(wù)器
const express = require('express')
const path = require('path')
let app = express()
app.get('/',(req,res)=>{
// 發(fā)送響應(yīng) 一個(gè)html的img圖片
res.send('<img src="/src/image/2444379.png"/ art="圖片">')
})
app.listen(8000,(err) => {
if(err) throw err
console.log('服務(wù)器開啟成功')
})
# 配置nginx
worker_processes 1;
events {
worker_connections 1024;
}
http {
include mime.types;
default_type application/octet-stream;
sendfile on;
keepalive_timeout 65;
upstream resource {
server 127.0.0.1:8000;
}
server {
listen 80;
server_name localhost;
location / {
proxy_pass http://resource;
}
# 訪問圖片
location ~ .*\.(js|css|html|htm|gif|png|jpg|jpeg|bmp|swf|icon|rar|zip|txt|flv|mid|doc|ppt|pdf|xls|mp3|mp4|wma)$ {
root static;
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root html;
}
}
}
動(dòng)靜分離
Nginx 的負(fù)載均衡和靜態(tài)代理結(jié)合在一起,我們就可以實(shí)現(xiàn)動(dòng)靜分離,這是實(shí)際應(yīng)用中常見的一種場(chǎng)景;
動(dòng)態(tài)資源,如jsp有tomact或其他web服務(wù)器完成
靜態(tài)資源,如圖片、css、js等由nginx服務(wù)器完成
配置如下
// 8000 服務(wù)器
const express = require('express')
const path = require('path')
let app = express()
app.get('/',(req,res)=>{
res.send('<img src="/src/image/2444379.png"/ art="圖片">')
})
app.listen(8001,(err) => {
if(err) throw err
console.log('服務(wù)器開啟成功')
})
// 8001 服務(wù)器
const express = require('express')
const path = require('path')
let app = express()
app.get('/',(req,res)=>{
res.send('<img src="/src/image/2444379.png"/ art="圖片">')
})
app.listen(8001,(err) => {
if(err) throw err
console.log('服務(wù)器開啟成功')
})
worker_processes 1;
events {
worker_connections 1024;
}
http {
include mime.types;
default_type application/octet-stream;
sendfile on;
keepalive_timeout 65;
# 配置 動(dòng)態(tài)資源
upstream resource {
server 127.0.0.1:8000;
server 127.0.0.1:8001;
}
# 配置 靜態(tài)資源
upstream staticResource {
server 127.0.0.1:8080;
}
server {
listen 80;
server_name localhost;
location / {
proxy_pass http://resource;
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root html;
}
}
server {
listen 8080;
server_name localhost;
# 訪問圖片
# location ~ .*\.(js|css|html|htm|gif|png|jpg|jpeg|bmp|swf|icon|rar|zip|txt|flv|mid|doc|ppt|pdf|xls|mp3|mp4|wma)$ {
# root static;
# }
location ~ .*/(css|img|js|images){
root static;
}
}
}
虛擬主機(jī)
虛擬主機(jī),就是把一臺(tái)物理服務(wù)器劃分成多個(gè) “ 虛擬 ” 的服務(wù)器,這樣我們的一臺(tái)物理服務(wù)器就可以當(dāng)做多個(gè)服務(wù)器來(lái)使用,從而配置多個(gè)服務(wù)器;
Nginx提供虛擬主機(jī)的功能,就是為了讓我們不需要安裝對(duì)個(gè)Nginx,就可以運(yùn)行多個(gè)網(wǎng)站
Nginx下,一個(gè)server標(biāo)簽就是一個(gè)虛擬主機(jī)
nginx的虛擬主機(jī)就是通過nginx.conf 中 server 節(jié)點(diǎn)指定的 , 想要設(shè)置多個(gè)虛擬主機(jī),配置多個(gè)server即可
-
基于端口的虛擬主機(jī)
基于端口的虛擬主機(jī)配置,使用端口來(lái)區(qū)分
-
瀏覽器使用 同一個(gè)域名 + 端口 或 同一個(gè)IP地址 + 端口訪問
server { listen 80; server_name localhost; location / { proxy_pass http://resource; } } server { listen 81; server_name localhost; location / { proxy_pass http://resource; } }
-
基于域名的虛擬主機(jī)
-
基于域名的虛擬主機(jī)是最常見的一種虛擬主機(jī)
server { listen 80; server_name www.shop.com; location / { root www; index index.html index.htm; } }
-
-
配置虛擬主機(jī)
# 此時(shí)域名無(wú)法被解析 需要修改hosts文件 server { listen 80; server_name myblogsing.com; location / { root www; index index.html index.htm; } }-
修改hosts文件,實(shí)現(xiàn)本地域名重定向
- C:\Windows\System32\drivers\etc\hosts 文件
# Copyright (c) 1993-2009 Microsoft Corp. # # This is a sample HOSTS file used by Microsoft TCP/IP for Windows. # # This file contains the mappings of IP addresses to host names. Each # entry should be kept on an individual line. The IP address should # be placed in the first column followed by the corresponding host name. # The IP address and the host name should be separated by at least one # space. # # Additionally, comments (such as these) may be inserted on individual # lines or following the machine name denoted by a '#' symbol. # # For example: # # 102.54.94.97 rhino.acme.com # source server # 38.25.63.10 x.acme.com # x client host # localhost name resolution is handled within DNS itself. # 127.0.0.1 localhost # ::1 localhost # 新增 域名重定向 127.0.0.1 myblogsing.com
-
- 使用include 的方式引入虛擬主機(jī)配置
- include /test/demo.conf
- 將虛擬目錄的配置文件加入到“http{}” 部分的末尾,與其他server并列
nginx 安裝模塊
gzip
gzip on : 打開或關(guān)閉gzip
-
gzip_buffers : 設(shè)置用于處理請(qǐng)求亞索的緩沖器數(shù)量和大小
gzip on; #32 4k 表示安裝內(nèi)存頁(yè)大小 以4k為單位,申請(qǐng)32倍內(nèi)存空間 gzip_buffers 32 4k|16 8k; -
gzip_comp_level :設(shè)置gzip壓縮幾倍,級(jí)別越低壓縮速度越快文件壓縮比越小,反速度越慢文件壓縮比越大
gzip on; gzip_comp_level 1;我們以一個(gè)大小為92.6K的腳本文件為例,如下所示。其中最后三個(gè)數(shù)值分別表示壓縮比、包大小、平均處理時(shí)間(使用ab壓測(cè),100用戶并發(fā)下,
./ab -n 10000 -c 100 -H 'Accept-Encoding: gzip' http://10.27.180.75/jquery.js)以及CPU消耗。從這我們可以得出結(jié)論:
- 隨著壓縮級(jí)別的升高,壓縮比有所提高,但到了級(jí)別6后,很難再提高;
- 隨著壓縮級(jí)別的升高,處理時(shí)間明顯變慢;
- gzip很消耗cpu的性能,高并發(fā)情況下cpu達(dá)到100%;
因此,建議:
- 不是壓縮級(jí)別越高越好,其實(shí)gzip_comp_level 1的壓縮能力已經(jīng)夠用了,后面級(jí)別越高,壓縮的比例其實(shí)增長(zhǎng)不大,反而很吃處理性能。
- 壓縮一定要和靜態(tài)資源緩存相結(jié)合,緩存壓縮后的版本,否則每次都?jí)嚎s高負(fù)載下服務(wù)器肯定吃不住。
-
**gzip_disable 通過表達(dá)式,表明那些UserAgent有不使用gzip **
Syntax: gzip_disable regex ...; Default: — Context: http, server, location This directive appeared in version 0.6.23. -
gzip_min_length: 當(dāng)返回內(nèi)容大于此指時(shí)才會(huì)使用gzip進(jìn)行壓縮 以k為單位,所有頁(yè)面都?jí)嚎s
gzip on; gzip_min_length 20; -
gzip_http_version: 識(shí)別http版本,早期瀏覽器不支持gzip,因此添加該屬性
gzip on; gzip_http_version 1.1; -
gzip_proxied
Nginx做為反向代理的時(shí)候啟用:
- off – 關(guān)閉所有的代理結(jié)果數(shù)據(jù)壓縮
- expired – 如果header中包含”Expires”頭信息,啟用壓縮
- no-cache – 如果header中包含”Cache-Control:no-cache”頭信息,啟用壓縮
- no-store – 如果header中包含”Cache-Control:no-store”頭信息,啟用壓縮
- private – 如果header中包含”Cache-Control:private”頭信息,啟用壓縮
- no_last_modified – 啟用壓縮,如果header中包含”Last_Modified”頭信息,啟用壓縮
- no_etag – 啟用壓縮,如果header中包含“ETag”頭信息,啟用壓縮
- auth – 啟用壓縮,如果header中包含“Authorization”頭信息,啟用壓縮
- any – 無(wú)條件壓縮所有結(jié)果數(shù)據(jù)
Syntax: gzip_proxied off | expired | no-cache | no-store | private | no_last_modified | no_etag | auth | any ...; Default: gzip_proxied off; Context: http, server, location -
gzip_vary: 增加響應(yīng)頭“Vary : Accept-Encoding”
Syntax: gzip_vary on | off; Default: gzip_vary off; Context: http, server, location -
gzip_types 設(shè)置需要壓縮的MIME類型,如果不在設(shè)置類型范圍內(nèi)的請(qǐng)求不進(jìn)行壓縮
字體類型擴(kuò)展名 Content-type .eot application/vnd.ms-fontobject .ttf font/ttf .otf font/opentype .woff font/x-woff .svg image/svg+xml
瀏覽器過期設(shè)置
- 設(shè)置緩存過期 expires
expires 20h