Nginx 配置文件在線生成: https://nginxconfig.io/
一、Nginx介紹Nginx是一款面向性能設計的 HTTP 伺服器,能反向代理 HTTP,HTTPS 和郵件相關(SMTP,POP3,IMAP)的協議連結。並且提供了負載均衡以及 HTTP 緩存。它的設計充分使用異步事件模型,削減上下文調度的開銷,提高伺服器並發能力。採用了模塊化設計,提供了豐富模塊的第三方模塊。
所以關於 Nginx,有這些標籤:「異步」「事件」「模塊化」「高性能」「高並發」「反向代理」「負載均衡」
二、安裝 2.1 安裝依賴prce(重定向支持)和openssl(https支持,如果不需要https可以不安裝。)
yum install -y pcre-devel
yum -y install gcc make gcc-c++ wget
yum -y install openssl openssl-develCentOS 6.5 我安裝的時候是選擇的「基本伺服器」,默認這兩個包都沒安裝全,所以這兩個都運行安裝即可。
2.2 下載nginx的所有版本在這裡 http://nginx.org/download/
wget http://nginx.org/download/nginx-1.13.3.tar.gz
wget http://nginx.org/download/nginx-1.13.7.tar.gz
# 如果沒有安裝wget
# 下載已編譯版本
$ yum install wget
# 解壓壓縮包
tar zxf nginx-1.13.3.tar.gz
2.3 編譯安裝然後進入目錄編譯安裝,configure參數說明
cd nginx-1.11.5
./configure
....
Configuration summary
+ using system PCRE library
+ OpenSSL library is not used
+ using system zlib library
nginx path prefix: "/usr/local/nginx"
nginx binary file: "/usr/local/nginx/sbin/nginx"
nginx modules path: "/usr/local/nginx/modules"
nginx configuration prefix: "/usr/local/nginx/conf"
nginx configuration file: "/usr/local/nginx/conf/nginx.conf"
nginx pid file: "/usr/local/nginx/logs/nginx.pid"
nginx error log file: "/usr/local/nginx/logs/error.log"
nginx http access log file: "/usr/local/nginx/logs/access.log"
nginx http client request body temporary files: "client_body_temp"
nginx http proxy temporary files: "proxy_temp"
nginx http fastcgi temporary files: "fastcgi_temp"
nginx http uwsgi temporary files: "uwsgi_temp"
nginx http scgi temporary files: "scgi_temp"安裝報錯誤的話比如:「C compiler cc is not found」,這個就是缺少編譯環境,安裝一下就可以了 yum -y install gcc make gcc-c++ openssl-devel
如果沒有error信息,就可以執行下邊的安裝了:
make
make install
2.4 nginx測試運行下面命令會出現兩個結果,一般情況nginx會安裝在/usr/local/nginx目錄中
cd /usr/local/nginx/sbin/
./nginx -t
# nginx: the configuration file /usr/local/nginx/conf/nginx.conf syntax is ok
# nginx: configuration file /usr/local/nginx/conf/nginx.conf test is successful
2.5 設置全局nginx命令vi ~/.bash_profile將下面內容添加到 ~/.bash_profile 文件中
PATH=$PATH:$HOME/bin:/usr/local/nginx/sbin/
export PATH運行命令 source ~/.bash_profile 讓配置立即生效。你就可以全局運行 nginx 命令了。
三、開機自啟動開機自啟動方法一:
編輯 vi /lib/systemd/system/nginx.service 文件,沒有創建一個 touch nginx.service 然後將如下內容根據具體情況進行修改後,添加到nginx.service文件中:
[Unit]
Description=nginx
After=network.target remote-fs.target nss-lookup.target
[Service]
Type=forking
PIDFile=/var/run/nginx.pid
ExecStartPre=/usr/local/nginx/sbin/nginx -t -c /usr/local/nginx/conf/nginx.conf
ExecStart=/usr/local/nginx/sbin/nginx -c /usr/local/nginx/conf/nginx.conf
ExecReload=/bin/kill -s HUP $MAINPID
ExecStop=/bin/kill -s QUIT $MAINPID
PrivateTmp=true
[Install]
WantedBy=multi-user.target
PrivateTmp=True表示給服務分配獨立的臨時空間注意:[Service]的啟動、重啟、停止命令全部要求使用絕對路徑
[Install]運行級別下服務安裝的相關設置,可設置為多用戶,即系統運行級別為3systemctl enable nginx.service
# 輸出下面內容表示成功了
Created symlink from /etc/systemd/system/multi-user.target.wants/nginx.service to /usr/lib/systemd/system/nginx.service.開機自啟動方法二:
vi /etc/rc.local
# 在 rc.local 文件中,添加下面這條命令
/usr/local/nginx/sbin/nginx start如果開機後發現自啟動腳本沒有執行,你要去確認一下rc.local這個文件的訪問權限是否是可執行的,因為rc.local默認是不可執行的。修改rc.local訪問權限,增加可執行權限:
chmod +x /etc/rc.d/rc.local
四、運維 4.1 服務管理# 啟動
/usr/local/nginx/sbin/nginx
# 重啟
/usr/local/nginx/sbin/nginx -s reload
# 關閉進程
/usr/local/nginx/sbin/nginx -s stop
# 平滑關閉nginx
/usr/local/nginx/sbin/nginx -s quit
# 查看nginx的安裝狀態,
/usr/local/nginx/sbin/nginx -V關閉防火牆,或者添加防火牆規則就可以測試了
service iptables stop或者編輯配置文件:
vi /etc/sysconfig/iptables添加這樣一條開放80埠的規則後保存:
-A INPUT -m state --state NEW -m tcp -p tcp --dport 80 -j ACCEPT重啟服務即可:
service iptables restart
# 命令進行查看目前nat
iptables -t nat -L
4.2 重啟服務防火牆報錯解決service iptables restart
# Redirecting to /bin/systemctl restart iptables.service
# Failed to restart iptables.service: Unit iptables.service failed to load: No such file or directory.在CentOS 7或RHEL 7或Fedora中防火牆由 firewalld 來管理,當然你可以還原傳統的管理方式。或則使用新的命令進行管理。假如採用傳統請執行一下命令:
# 傳統命令
systemctl stop firewalld
systemctl mask firewalld# 安裝命令
yum install iptables-services
systemctl enable iptables
service iptables restart
五、nginx卸載如果通過yum安裝,使用下面命令安裝。
yum remove nginx
編譯安裝,刪除/usr/local/nginx目錄即可六、參數說明 參數說明--prefix=<path>Nginx安裝路徑。如果沒有指定,默認為 /usr/local/nginx。--sbin-path=<path>Nginx可執行文件安裝路徑。只能安裝時指定,如果沒有指定,默認為<prefix>/sbin/nginx。--conf-path=<path>在沒有給定-c選項下默認的nginx.conf的路徑。如果沒有指定,默認為<prefix>/conf/nginx.conf`。--pid-path=<path>在nginx.conf中沒有指定pid指令的情況下,默認的nginx.pid的路徑。如果沒有指定,默認為 <prefix>/logs/nginx.pid。--lock-path=<path>nginx.lock文件的路徑。--error-log-path=<path>在nginx.conf中沒有指定error_log指令的情況下,默認的錯誤日誌的路徑。如果沒有指定,默認為 <prefix>/- logs/error.log。--http-log-path=<path>在nginx.conf中沒有指定access_log指令的情況下,默認的訪問日誌的路徑。如果沒有指定,默認為 <prefix>/- logs/access.log。--user=<user>在nginx.conf中沒有指定user指令的情況下,默認的nginx使用的用戶。如果沒有指定,默認為 nobody。--group=<group>在nginx.conf中沒有指定user指令的情況下,默認的nginx使用的組。如果沒有指定,默認為 nobody。--builddir=DIR指定編譯的目錄--with-rtsig_module啟用 rtsig 模塊--with-select_module --without-select_module允許或不允許開啟SELECT模式,如果configure 沒有找到更合適的模式,比如:kqueue(sun os),epoll (linux kenel 2.6+),rtsig(- 實時信號)或者/dev/poll(一種類似select的模式,底層實現與SELECT基本相 同,都是採用輪訓方法) SELECT模式將是默認安裝模式--with-poll_module --without-poll_moduleWhether or not to enable the poll module. This module is enabled by, default if a more suitable method such as kqueue, epoll, rtsig or /dev/poll is not discovered by configure.--with-http_ssl_moduleEnable ngx_http_ssl_module. Enables SSL support and the ability to handle HTTPS requests. Requires OpenSSL. On Debian, this is libssl-dev. 開啟HTTP SSL模塊,使NGINX可以支持HTTPS請求。這個模塊需要已經安裝了OPENSSL,在DEBIAN上是libssl--with-http_realip_module啟用 ngx_http_realip_module--with-http_addition_module啟用 ngx_http_addition_module--with-http_sub_module啟用 ngx_http_sub_module--with-http_dav_module啟用 ngx_http_dav_module--with-http_flv_module啟用 ngx_http_flv_module--with-http_stub_status_module啟用 "server status"頁--without-http_charset_module禁用 ngx_http_charset_module--without-http_gzip_module禁用 ngx_http_gzip_module. 如果啟用,需要 zlib 。--without-http_ssi_module禁用 ngx_http_ssi_module--without-http_userid_module禁用 ngx_http_userid_module--without-http_access_module禁用 ngx_http_access_module--without-http_auth_basic_module禁用 ngx_http_auth_basic_module--without-http_autoindex_module禁用 ngx_http_autoindex_module--without-http_geo_module禁用 ngx_http_geo_module--without-http_map_module禁用 ngx_http_map_module--without-http_referer_module禁用 ngx_http_referer_module--without-http_rewrite_module禁用 ngx_http_rewrite_module. 如果啟用需要PCRE 。--without-http_proxy_module禁用 ngx_http_proxy_module--without-http_fastcgi_module禁用 ngx_http_fastcgi_module--without-http_memcached_module禁用 ngx_http_memcached_module--without-http_limit_zone_module禁用 ngx_http_limit_zone_module--without-http_empty_gif_module禁用 ngx_http_empty_gif_module--without-http_browser_module禁用 ngx_http_browser_module--without-http_upstream_ip_hash_module禁用 ngx_http_upstream_ip_hash_module`--with-http_perl_module啟用 ngx_http_perl_module--with-perl_modules_path=PATH指定 perl 模塊的路徑--with-perl=PATH指定 perl 執行文件的路徑--http-log-path=PATHSet path to the http access log--http-client-body-temp-path=PATHSet path to the http client request body temporary files--http-proxy-temp-path=PATHSet path to the http proxy temporary files--http-fastcgi-temp-path=PATHSet path to the http fastcgi temporary files--without-http禁用 HTTP server--with-mail啟用 IMAP4/POP3/SMTP 代理模塊--with-mail_ssl_module啟用 ngx_mail_ssl_module--with-cc=PATH指定 C 編譯器的路徑--with-cpp=PATH指定 C 預處理器的路徑--with-cc-opt=OPTIONSAdditional parameters which will be added to the variable CFLAGS. With the use of the system library PCRE in FreeBSD, it is necessary to indicate --with-cc-opt="-I /usr/local/include". If we are using select() and it is necessary to increase the number of file descriptors, then this also can be assigned here: --with-cc-opt="-D FD_SETSIZE=2048".--with-ld-opt=OPTIONSAdditional parameters passed to the linker. With the use of the system library PCRE in - FreeBSD, it is necessary to indicate --with-ld-opt="-L /usr/local/lib".--with-cpu-opt=CPU為特定的 CPU 編譯,有效的值包括:pentium, pentiumpro, pentium3, pentium4, athlon, opteron, amd64, sparc32, sparc64, ppc64--without-pcre禁止 PCRE 庫的使用。同時也會禁止 HTTP rewrite 模塊。在 "location" 配置指令中的正則表達式也需要 PCRE 。--with-pcre=DIR指定 PCRE 庫的原始碼的路徑。--with-pcre-opt=OPTIONSSet additional options for PCRE building.--with-md5=DIRSet path to md5 library sources.--with-md5-opt=OPTIONSSet additional options for md5 building.--with-md5-asmUse md5 assembler sources.--with-sha1=DIRSet path to sha1 library sources.--with-sha1-opt=OPTIONSSet additional options for sha1 building.--with-sha1-asmUse sha1 assembler sources.--with-zlib=DIRSet path to zlib library sources.--with-zlib-opt=OPTIONSSet additional options for zlib building.--with-zlib-asm=CPUUse zlib assembler sources optimized for specified CPU, valid values are: pentium, pentiumpro--with-openssl=DIRSet path to OpenSSL library sources--with-openssl-opt=OPTIONSSet additional options for OpenSSL building--with-debug啟用調試日誌--add-module=PATHAdd in a third-party module found in directory PATH七、配置在Centos 默認配置文件在 /usr/local/nginx-1.5.1/conf/nginx.conf 我們要在這裡配置一些文件。nginx.conf是主配置文件,由若干個部分組成,每個大括號{}表示一個部分。每一行指令都由分號結束;,標誌著一行的結束。
7.1 常用正則正則說明正則說明.匹配除換行符以外的任意字符$匹配字符串的結束?重複0次或1次{n}重複n次+重複1次或更多次{n,}重複n次或更多次*重複0次或更多次[c]匹配單個字符c\d匹配數字[a-z]匹配a-z小寫字母的任意一個^匹配字符串的開始--7.2 全局變量變量說明變量說明$args這個變量等於請求行中的參數,同$query_string$remote_port客戶端的埠。$content_length請求頭中的Content-length欄位。$remote_user已經經過Auth Basic Module驗證的用戶名。$content_type請求頭中的Content-Type欄位。$request_filename當前請求的文件路徑,由root或alias指令與URI請求生成。$document_root當前請求在root指令中指定的值。$schemeHTTP方法(如http,https)。$host請求主機頭欄位,否則為伺服器名稱。$server_protocol請求使用的協議,通常是HTTP/1.0或HTTP/1.1。$http_user_agent客戶端agent信息$server_addr伺服器地址,在完成一次系統調用後可以確定這個值。$http_cookie客戶端cookie信息$server_name伺服器名稱。$limit_rate這個變量可以限制連接速率。$server_port請求到達伺服器的埠號。$request_method客戶端請求的動作,通常為GET或POST。$request_uri包含請求參數的原始URI,不包含主機名,如:/foo/bar.php?arg=baz。$remote_addr客戶端的IP位址。$uri不帶請求參數的當前URI,$uri不包含主機名,如/foo/bar.html。$document_uri與$uri`相同。--例如請求:http://localhost:3000/test1/test2/test.php
$host:localhost
$server_port:3000
$request_uri:/test1/test2/test.php
$document_uri:/test1/test2/test.php
$document_root:/var/www/html
$request_filename:/var/www/html/test1/test2/test.php
7.3 符號參考符號說明符號說明符號說明k,K千字節m,M兆字節ms毫秒s秒m分鐘h小時d日w周M一個月, 30天例如,"8k","1m" 代表字節數計量。
7.4 配置文件
例如,"1h 30m","1y 6M"。代表 "1小時 30分","1年零6個月"。nginx 的配置系統由一個主配置文件和其他一些輔助的配置文件構成。這些配置文件均是純文本文件,全部位於 nginx 安裝目錄下的 conf 目錄下。
指令由 nginx 的各個模塊提供,不同的模塊會提供不同的指令來實現配置。指令除了Key-Value 的形式,還有作用域指令。nginx.conf 中的配置信息,根據其邏輯上的意義,對它們進行了分類,也就是分成了多個作用域,或者稱之為配置指令上下文。不同的作用域含有一個或者多個配置項。下面的這些上下文指令用的比較多
DirectiveDescriptionContains Directivemainnginx 在運行時與具體業務功能(比如 http 服務或者 email 服務代理)無關的一些參數,比如工作進程數,運行的身份等。user, worker_processes, error_log, events, http, mailhttp與提供 http 服務相關的一些配置參數。例如:是否使用 keepalive 啊,是否使用 gzip 進行壓縮等。serverserverhttp 服務支持若干虛擬主機。每個虛擬主機一個對應的 server 配置項,配置項裡面包含該虛擬主機相關的配置。在提供 mail 服務的代理時,也可以建立若干 server. 每個 server 通過監聽的地址來區分。listen, server_name, access_log, location, protocol, proxy, smtp_auth, xclientlocationhttp 服務中,某些特定的 URL對應的一系列配置項。index, rootmail實現 email 相關的 SMTP/IMAP/POP3 代理時,共享的一些配置項(因為可能實現多個代理,工作在多個監聽地址上)。server, http,imap_capabilitiesinclude以便增強配置文件的可讀性,使得部分配置文件可以重新使用。-valid_referers用來校驗Http請求頭Referer是否有效。-try_files用在server部分,不過最常見的還是用在location部分,它會按照給定的參數順序進行嘗試,第一個被匹配到的將會被使用。-if當在location塊中使用if指令,在某些情況下它並不按照預期運行,一般來說避免使用if指令。-例如我們在 nginx.conf 裡面引用兩個配置 vhost/example.com.conf 和 vhost/gitlab.com.conf 它們都被放在一個我自己新建的目錄 vhost 下面。nginx.conf 配置如下:
worker_processes 1;
events {
worker_connections 1024;
}
http {
include mime.types;
default_type application/octet-stream;
#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 logs/access.log main;
sendfile on;
#tcp_nopush on;
#keepalive_timeout 0;
keepalive_timeout 65;
#gzip on;
server {
listen 80;
server_name localhost;
location / {
root html;
index index.html index.htm;
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root html;
}
}
include vhost/example.com.conf;
include vhost/gitlab.com.conf;
}簡單的配置: example.com.conf
server {
#偵聽的80埠
listen 80;
server_name baidu.com app.baidu.com; # 這裡指定域名
index index.html index.htm; # 這裡指定默認入口頁面
root /home/www/app.baidu.com; # 這裡指定目錄
}
7.5 內置預定義變量Nginx提供了許多預定義的變量,也可以通過使用set來設置變量。你可以在if中使用預定義變量,也可以將它們傳遞給代理伺服器。以下是一些常見的預定義變量,更多詳見
變量名稱值$args_name在請求中的name參數$args所有請求參數$query_string$args的別名$content_length請求頭Content-Length的值$content_type請求頭Content-Type的值$host如果當前有Host,則為請求頭Host的值;如果沒有這個頭,那麼該值等於匹配該請求的server_name的值$remote_addr客戶端的IP位址$request完整的請求,從客戶端收到,包括Http請求方法、URI、Http協議、頭、請求體$request_uri完整請求的URI,從客戶端來的請求,包括參數$scheme當前請求的協議$uri當前請求的標準化URI7.6 反向代理反向代理是一個Web伺服器,它接受客戶端的連接請求,然後將請求轉發給上遊伺服器,並將從伺服器得到的結果返回給連接的客戶端。下面簡單的反向代理的例子:
server {
listen 80;
server_name localhost;
client_max_body_size 1024M; # 允許客戶端請求的最大單文件字節數
location / {
proxy_pass http://localhost:8080;
proxy_set_header Host $host:$server_port;
proxy_set_header X-Forwarded-For $remote_addr; # HTTP的請求端真實的IP
proxy_set_header X-Forwarded-Proto $scheme; # 為了正確地識別實際用戶發出的協議是 http 還是 https
}
}複雜的配置: gitlab.com.conf。
server {
#偵聽的80埠
listen 80;
server_name git.example.cn;
location / {
proxy_pass http://localhost:3000;
#以下是一些反向代理的配置可刪除
proxy_redirect off;
#後端的Web伺服器可以通過X-Forwarded-For獲取用戶真實IP
proxy_set_header Host $host;
client_max_body_size 10m; #允許客戶端請求的最大單文件字節數
client_body_buffer_size 128k; #緩衝區代理緩衝用戶端請求的最大字節數
proxy_connect_timeout 300; #nginx跟後端伺服器連接超時時間(代理連接超時)
proxy_send_timeout 300; #後端伺服器數據回傳時間(代理髮送超時)
proxy_read_timeout 300; #連接成功後,後端伺服器響應時間(代理接收超時)
proxy_buffer_size 4k; #設置代理伺服器(nginx)保存用戶頭信息的緩衝區大小
proxy_buffers 4 32k; #proxy_buffers緩衝區,網頁平均在32k以下的話,這樣設置
proxy_busy_buffers_size 64k; #高負荷下緩衝大小(proxy_buffers*2)
}
}代理到上遊伺服器的配置中,最重要的是proxy_pass指令。以下是代理模塊中的一些常用指令:
指令說明proxy_connect_timeoutNginx從接受請求至連接到上遊伺服器的最長等待時間proxy_send_timeout後端伺服器數據回傳時間(代理髮送超時)proxy_read_timeout連接成功後,後端伺服器響應時間(代理接收超時)proxy_cookie_domain替代從上遊伺服器來的Set-Cookie頭的domain屬性proxy_cookie_path替代從上遊伺服器來的Set-Cookie頭的path屬性proxy_buffer_size設置代理伺服器(nginx)保存用戶頭信息的緩衝區大小proxy_buffersproxy_buffers緩衝區,網頁平均在多少k以下proxy_set_header重寫發送到上遊伺服器頭的內容,也可以通過將某個頭部的值設置為空字符串,而不發送某個頭部的方法實現proxy_ignore_headers這個指令禁止處理來自代理伺服器的應答。proxy_intercept_errors使nginx阻止HTTP應答代碼為400或者更高的應答。7.7 負載均衡upstream指令啟用一個新的配置區段,在該區段定義一組上遊伺服器。這些伺服器可能被設置不同的權重,也可能出於對伺服器進行維護,標記為down。
upstream gitlab {
ip_hash;
# upstream的負載均衡,weight是權重,可以根據機器配置定義權重。weigth參數表示權值,權值越高被分配到的機率越大。
server 192.168.122.11:8081 ;
server 127.0.0.1:82 weight=3;
server 127.0.0.1:83 weight=3 down;
server 127.0.0.1:84 weight=3; max_fails=3 fail_timeout=20s;
server 127.0.0.1:85 weight=4;;
keepalive 32;
}
server {
#偵聽的80埠
listen 80;
server_name git.example.cn;
location / {
proxy_pass http://gitlab; #在這裡設置一個代理,和upstream的名字一樣
#以下是一些反向代理的配置可刪除
proxy_redirect off;
#後端的Web伺服器可以通過X-Forwarded-For獲取用戶真實IP
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
client_max_body_size 10m; #允許客戶端請求的最大單文件字節數
client_body_buffer_size 128k; #緩衝區代理緩衝用戶端請求的最大字節數
proxy_connect_timeout 300; #nginx跟後端伺服器連接超時時間(代理連接超時)
proxy_send_timeout 300; #後端伺服器數據回傳時間(代理髮送超時)
proxy_read_timeout 300; #連接成功後,後端伺服器響應時間(代理接收超時)
proxy_buffer_size 4k; #設置代理伺服器(nginx)保存用戶頭信息的緩衝區大小
proxy_buffers 4 32k;# 緩衝區,網頁平均在32k以下的話,這樣設置
proxy_busy_buffers_size 64k; #高負荷下緩衝大小(proxy_buffers*2)
proxy_temp_file_write_size 64k; #設定緩存文件夾大小,大於這個值,將從upstream伺服器傳
}
}每個請求按時間順序逐一分配到不同的後端伺服器,如果後端伺服器down掉,能自動剔除。
負載均衡:
upstream模塊能夠使用3種負載均衡算法:輪詢、IP哈希、最少連接數。
輪詢: 默認情況下使用輪詢算法,不需要配置指令來激活它,它是基於在隊列中誰是下一個的原理確保訪問均勻地分布到每個上遊伺服器;
7.7.1 RR
IP哈希: 通過ip_hash指令來激活,Nginx通過IPv4地址的前3個字節或者整個IPv6地址作為哈希鍵來實現,同一個IP位址總是能被映射到同一個上遊伺服器;
最少連接數: 通過least_conn指令來激活,該算法通過選擇一個活躍數最少的上遊伺服器進行連接。如果上遊伺服器處理能力不同,可以通過給server配置weight權重來說明,該算法將考慮到不同伺服器的加權最少連接數。簡單配置 ,這裡我配置了2臺伺服器,當然實際上是一臺,只是埠不一樣而已,而8081的伺服器是不存在的,也就是說訪問不到,但是我們訪問 http://localhost 的時候,也不會有問題,會默認跳轉到http://localhost:8080具體是因為Nginx會自動判斷伺服器的狀態,如果伺服器處於不能訪問(伺服器掛了),就不會跳轉到這臺伺服器,所以也避免了一臺伺服器掛了影響使用的情況,由於Nginx默認是RR策略,所以我們不需要其他更多的設置
upstream test {
server localhost:8080;
server localhost:8081;
}
server {
listen 81;
server_name localhost;
client_max_body_size 1024M;
location / {
proxy_pass http://test;
proxy_set_header Host $host:$server_port;
}
}負載均衡的核心代碼為
upstream test {
server localhost:8080;
server localhost:8081;
}
7.7.2 權重指定輪詢機率,weight和訪問比率成正比,用於後端伺服器性能不均的情況。例如
upstream test {
server localhost:8080 weight=9;
server localhost:8081 weight=1;
}那麼10次一般只會有1次會訪問到8081,而有9次會訪問到8080
7.7.3 ip_hash上面的2種方式都有一個問題,那就是下一個請求來的時候請求可能分發到另外一個伺服器,當我們的程序不是無狀態的時候(採用了session保存數據),這時候就有一個很大的很問題了,比如把登錄信息保存到了session中,那麼跳轉到另外一臺伺服器的時候就需要重新登錄了,所以很多時候我們需要一個客戶只訪問一個伺服器,那麼就需要用iphash了,iphash的每個請求按訪問ip的hash結果分配,這樣每個訪客固定訪問一個後端伺服器,可以解決session的問題。
upstream test {
ip_hash;
server localhost:8080;
server localhost:8081;
}
7.7.4 fair這是個第三方模塊,按後端伺服器的響應時間來分配請求,響應時間短的優先分配。
upstream backend {
fair;
server localhost:8080;
server localhost:8081;
}
7.7.5 url_hash這是個第三方模塊,按訪問url的hash結果來分配請求,使每個url定向到同一個後端伺服器,後端伺服器為緩存時比較有效。在upstream中加入hash語句,server語句中不能寫入weight等其他的參數,hash_method是使用的hash算法
upstream backend {
hash $request_uri;
hash_method crc32;
server localhost:8080;
server localhost:8081;
}以上5種負載均衡各自適用不同情況下使用,所以可以根據實際情況選擇使用哪種策略模式,不過fair和url_hash需要安裝第三方模塊才能使用
server指令可選參數:
weight:設置一個伺服器的訪問權重,數值越高,收到的請求也越多;fail_timeout:在這個指定的時間內伺服器必須提供響應,如果在這個時間內沒有收到響應,那麼伺服器將會被標記為down狀態;max_fails:設置在fail_timeout時間之內嘗試對一個伺服器連接的最大次數,如果超過這個次數,那麼伺服器將會被標記為down;backup:一旦其他伺服器宕機,那麼有該標記的機器將會接收請求。keepalive指令:
Nginx伺服器將會為每一個worker進行保持同上遊伺服器的連接。
7.8 屏蔽ip在nginx的配置文件nginx.conf中加入如下配置,可以放到http, server, location, limit_except語句塊,需要注意相對路徑,本例當中nginx.conf,blocksip.conf在同一個目錄中。
include blockip.conf;在blockip.conf裡面輸入內容,如:
deny 165.91.122.67;
deny IP; # 屏蔽單個ip訪問
allow IP; # 允許單個ip訪問
deny all; # 屏蔽所有ip訪問
allow all; # 允許所有ip訪問
deny 123.0.0.0/8 # 屏蔽整個段即從123.0.0.1到123.255.255.254訪問的命令
deny 124.45.0.0/16 # 屏蔽IP段即從123.45.0.1到123.45.255.254訪問的命令
deny 123.45.6.0/24 # 屏蔽IP段即從123.45.6.1到123.45.6.254訪問的命令
# 如果你想實現這樣的應用,除了幾個IP外,其他全部拒絕
allow 1.1.1.1;
allow 1.1.1.2;
deny all;
八、第三方模塊安裝方法./configure --prefix=/你的安裝目錄 --add-module=/第三方模塊目錄
九、重定向 permanent 永久性重定向。請求日誌中的狀態碼為301redirect 臨時重定向。請求日誌中的狀態碼為3029.1 重定向整個網站server {
server_name old-site.com
return 301 $scheme://new-site.com$request_uri;
}
9.2 重定向單頁server {
location = /oldpage.html {
return 301 http://example.org/newpage.html;
}
}
9.3 重定向整個子路徑location /old-site {
rewrite ^/old-site/(.*) http://example.org/new-site/$1 permanent;
}
十、性能 10.1 內容緩存允許瀏覽器基本上永久地緩存靜態內容。Nginx將為您設置Expires和Cache-Control頭信息。
location /static {
root /data;
expires max;
}如果要求瀏覽器永遠不會緩存響應(例如用於跟蹤請求),請使用-1。
location = /empty.gif {
empty_gif;
expires -1;
}
10.2 Gzip壓縮gzip on;
gzip_buffers 16 8k;
gzip_comp_level 6;
gzip_http_version 1.1;
gzip_min_length 256;
gzip_proxied any;
gzip_vary on;
gzip_types
text/xml application/xml application/atom+xml application/rss+xml application/xhtml+xml image/svg+xml
text/javascript application/javascript application/x-javascript
text/x-json application/json application/x-web-app-manifest+json
text/css text/plain text/x-component
font/opentype application/x-font-ttf application/vnd.ms-fontobject
image/x-icon;
gzip_disable "msie6";
10.3 打開文件緩存open_file_cache max=1000 inactive=20s;
open_file_cache_valid 30s;
open_file_cache_min_uses 2;
open_file_cache_errors on;
10.4 SSL緩存ssl_session_cache shared:SSL:10m;
ssl_session_timeout 10m;
10.5 上遊Keepaliveupstream backend {
server 127.0.0.1:8080;
keepalive 32;
}
server {
...
location /api/ {
proxy_pass http://backend;
proxy_http_version 1.1;
proxy_set_header Connection "";
}
}
10.6 監控使用ngxtop實時解析nginx訪問日誌,並且將處理結果輸出到終端,功能類似於系統命令top。所有示例都讀取nginx配置文件的訪問日誌位置和格式。如果要指定訪問日誌文件和/或日誌格式,請使用-f和-a選項。
注意:在nginx配置中/usr/local/nginx/conf/nginx.conf日誌文件必須是絕對路徑。
# 安裝 ngxtop
pip install ngxtop
# 實時狀態
ngxtop
# 狀態為404的前10個請求的路徑:
ngxtop top request_path --filter 'status == 404'
# 發送總字節數最多的前10個請求
ngxtop --order-by 'avg(bytes_sent) * count'
# 排名前十位的IP,例如,誰攻擊你最多
ngxtop --group-by remote_addr
# 列印具有4xx或5xx狀態的請求,以及status和http referer
ngxtop -i 'status >= 400' print request status http_referer
# 由200個請求路徑響應發送的平均正文字節以'foo'開始:
ngxtop avg bytes_sent --filter 'status == 200 and request_path.startswith("foo")'
# 使用「common」日誌格式從遠程機器分析apache訪問日誌
ssh remote tail -f /var/log/apache2/access.log | ngxtop -f common
十一、常見使用場景 11.1 跨域問題在工作中,有時候會遇到一些接口不支持跨域,這時候可以簡單的添加add_headers來支持cors跨域。配置如下:
server {
listen 80;
server_name api.xxx.com;
add_header 'Access-Control-Allow-Origin' '*';
add_header 'Access-Control-Allow-Credentials' 'true';
add_header 'Access-Control-Allow-Methods' 'GET,POST,HEAD';
location / {
proxy_pass http://127.0.0.1:3000;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header Host $http_host;
}
}上面更改頭信息,還有一種,使用 rewrite 指令重定向URI來解決跨域問題。
upstream test {
server 127.0.0.1:8080;
server localhost:8081;
}
server {
listen 80;
server_name api.xxx.com;
location / {
root html; #去請求../html文件夾裡的文件
index index.html index.htm; #首頁響應地址
}
# 用於攔截請求,匹配任何以 /api/開頭的地址,
# 匹配符合以後,停止往下搜索正則。
location ^~/api/{
# 代表重寫攔截進來的請求,並且只能對域名後邊的除去傳遞的參數外的字符串起作用,
# 例如www.a.com/proxy/api/msg?meth=1&par=2重寫,只對/proxy/api/msg重寫。
# rewrite後面的參數是一個簡單的正則 ^/api/(.*)$,
# $1代表正則中的第一個(),$2代表第二個()的值,以此類推。
rewrite ^/api/(.*)$ /$1 break;
# 把請求代理到其他主機
# 其中 http://www.b.com/ 寫法和 http://www.b.com寫法的區別如下
# 如果你的請求地址是他 http://server/html/test.jsp
# 配置一:http://www.b.com/ 後面有「/」
# 將反向代理成 http://www.b.com/html/test.jsp 訪問
# 配置一:http://www.b.com 後面沒有有「/」
# 將反向代理成 http://www.b.com/test.jsp 訪問
proxy_pass http://test;
# 如果 proxy_pass URL 是 http://a.xx.com/platform/ 這種情況
# proxy_cookie_path應該設置成 /platform/ / (注意兩個斜槓之間有空格)。
proxy_cookie_path /platfrom/ /;
# http://nginx.org/en/docs/http/ngx_http_proxy_module.html#proxy_pass_header
# 設置 Cookie 頭通過
proxy_pass_header Set-Cookie;
}
}
11.2 跳轉到帶www的域上面server {
listen 80;
# 配置正常的帶www的域名
server_name www.wangchujiang.com;
root /home/www/wabg/download;
location / {
try_files $uri $uri/ /index.html =404;
}
}
server {
# 這個要放到下面,
# 將不帶www的 wangchujiang.com 永久性重定向到 https://www.wangchujiang.com
server_name wangchujiang.com;
rewrite ^(.*) https://www.wangchujiang.com$1 permanent;
}
11.3 代理轉發upstream server-api{
# api 代理服務地址
server 127.0.0.1:3110;
}
upstream server-resource{
# 靜態資源 代理服務地址
server 127.0.0.1:3120;
}
server {
listen 3111;
server_name localhost; # 這裡指定域名
root /home/www/server-statics;
# 匹配 api 路由的反向代理到API服務
location ^~/api/ {
rewrite ^/(.*)$ /$1 break;
proxy_pass http://server-api;
}
# 假設這裡驗證碼也在API服務中
location ^~/captcha {
rewrite ^/(.*)$ /$1 break;
proxy_pass http://server-api;
}
# 假設你的圖片資源全部在另外一個服務上面
location ^~/img/ {
rewrite ^/(.*)$ /$1 break;
proxy_pass http://server-resource;
}
# 路由在前端,後端沒有真實路由,在路由不存在的 404狀態的頁面返回 /index.html
# 這個方式使用場景,你在寫React或者Vue項目的時候,沒有真實路由
location / {
try_files $uri $uri/ /index.html =404;
# ^ 空格很重要
}
}
11.4 代理轉發連接替換location ^~/api/upload {
rewrite ^/(.*)$ /wfs/v1/upload break;
proxy_pass http://wfs-api;
}
11.5 ssl配置超文本傳輸安全協議(縮寫:HTTPS,英語:Hypertext Transfer Protocol Secure)是超文本傳輸協議和SSL/TLS的組合,用以提供加密通訊及對網絡伺服器身份的鑑定。HTTPS連接經常被用於全球資訊網上的交易支付和企業信息系統中敏感信息的傳輸。HTTPS不應與在RFC 2660中定義的安全超文本傳輸協議(S-HTTP)相混。HTTPS 目前已經是所有注重隱私和安全的網站的首選,隨著技術的不斷發展,HTTPS 網站已不再是大型網站的專利,所有普通的個人站長和博客均可以自己動手搭建一個安全的加密的網站。
創建SSL證書,如果你購買的證書,就可以直接下載
sudo mkdir /etc/nginx/ssl
# 創建了有效期100年,加密強度為RSA2048的SSL密鑰key和X509證書文件。
sudo openssl req -x509 -nodes -days 36500 -newkey rsa:2048 -keyout /etc/nginx/ssl/nginx.key -out /etc/nginx/ssl/nginx.crt
# 上面命令,會有下面需要填寫內容
Country Name (2 letter code) [AU]:US
State or Province Name (full name) [Some-State]:New York
Locality Name (eg, city) []:New York City
Organization Name (eg, company) [Internet Widgits Pty Ltd]:Bouncy Castles, Inc.
Organizational Unit Name (eg, section) []:Ministry of Water Slides
Common Name (e.g. server FQDN or YOUR name) []:your_domain.com
Email Address []:admin@your_domain.com創建自籤證書
首先,創建證書和私鑰的目錄
# mkdir -p /etc/nginx/cert
# cd /etc/nginx/cert
創建伺服器私鑰,命令會讓你輸入一個口令:
# openssl genrsa -des3 -out nginx.key 2048
創建籤名請求的證書(CSR):
# openssl req -new -key nginx.key -out nginx.csr
在加載SSL支持的Nginx並使用上述私鑰時去必須的口令:
# cp nginx.key nginx.key.org
# openssl rsa -in nginx.key.org -out nginx.key
最後標記證書使用上述私鑰和CSR:
# openssl x509 -req -days 365 -in nginx.csr -signkey nginx.key -out nginx.crt查看目前nginx編譯選項
sbin/nginx -V輸出下面內容
nginx version: nginx/1.7.8
built by gcc 4.4.7 20120313 (Red Hat 4.4.7-4) (GCC)
TLS SNI support enabled
configure arguments: --prefix=/usr/local/nginx-1.7.8 --with-http_ssl_module --with-http_spdy_module --with-http_stub_status_module --with-pcre如果依賴的模塊不存在,可以進入安裝目錄,輸入下面命令重新編譯安裝。
./configure --prefix=/usr/local/nginx --with-http_stub_status_module --with-http_ssl_module運行完成之後還需要make (不用make install)
# 備份nginx的二進位文件
cp -rf /usr/local/nginx/sbin/nginx /usr/local/nginx/sbin/nginx.bak
# 覆蓋nginx的二進位文件
cp -rf objs/nginx /usr/local/nginx/sbin/HTTPS server
server {
listen 443 ssl;
server_name localhost;
ssl_certificate /etc/nginx/ssl/nginx.crt;
ssl_certificate_key /etc/nginx/ssl/nginx.key;
# 禁止在header中出現伺服器版本,防止黑客利用版本漏洞攻擊
server_tokens off;
# 設置ssl/tls會話緩存的類型和大小。如果設置了這個參數一般是shared,buildin可能會參數內存碎片,默認是none,和off差不多,停用緩存。如shared:SSL:10m表示我所有的nginx工作進程共享ssl會話緩存,官網介紹說1M可以存放約4000個sessions。
ssl_session_cache shared:SSL:1m;
# 客戶端可以重用會話緩存中ssl參數的過期時間,內網系統默認5分鐘太短了,可以設成30m即30分鐘甚至4h。
ssl_session_timeout 5m;
# 選擇加密套件,不同的瀏覽器所支持的套件(和順序)可能會不同。
# 這裡指定的是OpenSSL庫能夠識別的寫法,你可以通過 openssl -v cipher 'RC4:HIGH:!aNULL:!MD5'(後面是你所指定的套件加密算法) 來看所支持算法。
ssl_ciphers HIGH:!aNULL:!MD5;
# 設置協商加密算法時,優先使用我們服務端的加密套件,而不是客戶端瀏覽器的加密套件。
ssl_prefer_server_ciphers on;
location / {
root html;
index index.html index.htm;
}
}
11.6 強制將http重定向到httpsserver {
listen 80;
server_name example.com;
rewrite ^ https://$http_host$request_uri? permanent; # 強制將http重定向到https
# 在錯誤頁面和「伺服器」響應頭欄位中啟用或禁用發射nginx版本。防止黑客利用版本漏洞攻擊
server_tokens off;
}
11.7 兩個虛擬主機純靜態-html支持
http {
server {
listen 80;
server_name www.domain1.com;
access_log logs/domain1.access.log main;
location / {
index index.html;
root /var/www/domain1.com/htdocs;
}
}
server {
listen 80;
server_name www.domain2.com;
access_log logs/domain2.access.log main;
location / {
index index.html;
root /var/www/domain2.com/htdocs;
}
}
}
11.8 虛擬主機標準配置http {
server {
listen 80 default;
server_name _ *;
access_log logs/default.access.log main;
location / {
index index.html;
root /var/www/default/htdocs;
}
}
}
11.9 防盜鏈location ~* \.(gif|jpg|png|swf|flv)$ {
root html
valid_referers none blocked *.nginxcn.com;
if ($invalid_referer) {
rewrite ^/ www.nginx.cn
#return 404;
}
}
11.10虛擬目錄配置alias指定的目錄是準確的,root是指定目錄的上級目錄,並且該上級目錄要含有location指定名稱的同名目錄。
location /img/ {
alias /var/www/image/;
}
# 訪問/img/目錄裡面的文件時,ningx會自動去/var/www/image/目錄找文件
location /img/ {
root /var/www/image;
}
# 訪問/img/目錄下的文件時,nginx會去/var/www/image/img/目錄下找文件。]
11.11 防盜圖配置location ~ \/public\/(css|js|img)\/.*\.(js|css|gif|jpg|jpeg|png|bmp|swf) {
valid_referers none blocked *.jslite.io;
if ($invalid_referer) {
rewrite ^/ http://wangchujiang.com/piratesp.png;
}
}
11.12 屏蔽.git等文件location ~ (.git|.gitattributes|.gitignore|.svn) {
deny all;
}
11.13 域名路徑加不加需要都能正常訪問http://wangchujiang.com/api/index.php?a=1&name=wcj
^ 有後綴
http://wangchujiang.com/api/index?a=1&name=wcj
^ 沒有後綴nginx rewrite規則如下:
rewrite ^/(.*)/$ /index.php?/$1 permanent;
if (!-d $request_filename){
set $rule_1 1$rule_1;
}
if (!-f $request_filename){
set $rule_1 2$rule_1;
}
if ($rule_1 = "21"){
rewrite ^/ /index.php last;
}
十二、錯誤問題The plain HTTP request was sent to HTTPS port解決辦法,fastcgi_param HTTPS $https if_not_empty 添加這條規則,
server {
listen 443 ssl; # 注意這條規則
server_name my.domain.com;
fastcgi_param HTTPS $https if_not_empty;
fastcgi_param HTTPS on;
ssl_certificate /etc/ssl/certs/your.pem;
ssl_certificate_key /etc/ssl/private/your.key;
location / {
# Your config here...
}
}