安裝
安裝依賴
安裝 Nginx 之前,確保系統(tǒng)已經(jīng)安裝 gcc、openssl-devel、pcre-devel 和 zlib-devel 軟件庫(kù)
- gcc 可以通過(guò)光盤(pán)直接選擇安裝
- openssl-devel、zlib-devel 可以通過(guò)光盤(pán)直接選擇安裝,https 時(shí)使用
- pcre-devel 安裝 pcre 庫(kù)是為了使 nginx 支持 HTTP Rewrite 模塊
編譯安裝
通過(guò)上面的下載頁(yè)下載最新的穩(wěn)定版
#wget http://nginx.org/download/nginx-1.8.0.tar.gz
#tar xzvf nginx-1.8.0.tar.gz
#cd nginx-1.8.0
#./configure --prefix=/opt/X_nginx/nginx --with-http_ssl_module
#make && sudo make install
復(fù)制代碼
--prefix=/opt/X_nginx/nginx 安裝目錄 --with-http_ssl_module 添加 https 支持
編譯時(shí)將 ssl 模塊靜態(tài)編譯
./configure --prefix=/opt/X_nginx/nginx
--with-openssl=../openssl-1.0.2l
--with-zlib=../zlib-1.2.11
--with-pcre=../pcre-8.41
--with-http_ssl_module
復(fù)制代碼
nginx 服務(wù)架構(gòu)
模塊化結(jié)構(gòu)
nginx 服務(wù)器的開(kāi)發(fā)完全遵循模塊化設(shè)計(jì)思想
模塊化開(kāi)發(fā)
- 單一職責(zé)原則,一個(gè)模塊只負(fù)責(zé)一個(gè)功能
- 將程序分解,自頂向下,逐步求精
- 高內(nèi)聚,低耦合
nginx 的模塊化結(jié)構(gòu)
- 核心模塊:nginx 最基本最核心的服務(wù),如進(jìn)程管理、權(quán)限控制、日志記錄;
- 標(biāo)準(zhǔn) HTTP 模塊:nginx 服務(wù)器的標(biāo)準(zhǔn) HTTP 功能;
- 可選 HTTP 模塊:處理特殊的 HTTP 請(qǐng)求
- 郵件服務(wù)模塊:郵件服務(wù)
- 第三方模塊:作為擴(kuò)展,完成特殊功能
nginx 的模塊清單
- 核心模塊
- ngx_core
- ngx_errlog
- ngx_conf
- ngx_events
- ngx_event_core
- ngx_epll
- ngx_regex
- 標(biāo)準(zhǔn) HTTP 模塊
- ngx_http
- ngx_http_core #配置端口,URI 分析,服務(wù)器相應(yīng)錯(cuò)誤處理,別名控制 (alias) 等
- ngx_http_log #自定義 access 日志
- ngx_http_upstream #定義一組服務(wù)器,可以接受來(lái)自 proxy, Fastcgi,Memcache 的重定向;主要用作負(fù)載均衡
- ngx_http_static
- ngx_http_autoindex #自動(dòng)生成目錄列表
- ngx_http_index #處理以/結(jié)尾的請(qǐng)求,如果沒(méi)有找到 index 頁(yè),則看是否開(kāi)啟了random_index;如開(kāi)啟,則用之,否則用 autoindex
- ngx_http_auth_basic #基于 http 的身份認(rèn)證 (auth_basic)
- ngx_http_access #基于 IP 地址的訪問(wèn)控制 (deny,allow)
- ngx_http_limit_conn #限制來(lái)自客戶端的連接的響應(yīng)和處理速率
- ngx_http_limit_req #限制來(lái)自客戶端的請(qǐng)求的響應(yīng)和處理速率
- ngx_http_geo
- ngx_http_map #創(chuàng)建任意的鍵值對(duì)變量
- ngx_http_split_clients
- ngx_http_referer #過(guò)濾 HTTP 頭中 Referer 為空的對(duì)象
- ngx_http_rewrite #通過(guò)正則表達(dá)式重定向請(qǐng)求
- ngx_http_proxy
- ngx_http_fastcgi #支持 fastcgi
- ngx_http_uwsgi
- ngx_http_scgi
- ngx_http_memcached
- ngx_http_empty_gif #從內(nèi)存創(chuàng)建一個(gè) 1×1 的透明 gif 圖片,可以快速調(diào)用
- ngx_http_browser #解析 http 請(qǐng)求頭部的 User-Agent 值
- ngx_http_charset #指定網(wǎng)頁(yè)編碼
- ngx_http_upstream_ip_hash
- ngx_http_upstream_least_conn
- ngx_http_upstream_keepalive
- ngx_http_write_filter
- ngx_http_header_filter
- ngx_http_chunked_filter
- ngx_http_range_header
- ngx_http_gzip_filter
- ngx_http_postpone_filter
- ngx_http_ssi_filter
- ngx_http_charset_filter
- ngx_http_userid_filter
- ngx_http_headers_filter #設(shè)置 http 響應(yīng)頭
- ngx_http_copy_filter
- ngx_http_range_body_filter
- ngx_http_not_modified_filter
- 可選 HTTP 模塊
- ngx_http_addition #在響應(yīng)請(qǐng)求的頁(yè)面開(kāi)始或者結(jié)尾添加文本信息
- ngx_http_degradation #在低內(nèi)存的情況下允許服務(wù)器返回 444 或者 204 錯(cuò)誤
- ngx_http_perl
- ngx_http_flv #支持將 Flash 多媒體信息按照流文件傳輸,可以根據(jù)客戶端指定的開(kāi)始位置返回 Flash
- ngx_http_geoip #支持解析基于 GeoIP 數(shù)據(jù)庫(kù)的客戶端請(qǐng)求
- ngx_google_perftools
- ngx_http_gzip #gzip 壓縮請(qǐng)求的響應(yīng)
- ngx_http_gzip_static #搜索并使用預(yù)壓縮的以.gz 為后綴的文件代替一般文件響應(yīng)客戶端請(qǐng)求
- ngx_http_image_filter #支持改變 png,jpeg,gif 圖片的尺寸和旋轉(zhuǎn)方向
- ngx_http_mp4 #支持.mp4,.m4v,.m4a 等多媒體信息按照流文件傳輸,常與 ngx_http_flv 一起使用
- ngx_http_random_index #當(dāng)收到 / 結(jié)尾的請(qǐng)求時(shí),在指定目錄下隨機(jī)選擇一個(gè)文件作為 index
- ngx_http_secure_link #支持對(duì)請(qǐng)求鏈接的有效性檢查
- ngx_http_ssl #支持 https
- ngx_http_stub_status
- ngx_http_sub_module #使用指定的字符串替換響應(yīng)中的信息
- ngx_http_dav #支持 HTTP 和 WebDAV 協(xié)議中的 PUT/DELETE/MKCOL/COPY/MOVE 方法
- ngx_http_xslt #將 XML 響應(yīng)信息使用 XSLT 進(jìn)行轉(zhuǎn)換
- 郵件服務(wù)模塊
- ngx_mail_core
- ngx_mail_pop3
- ngx_mail_imap
- ngx_mail_smtp
- ngx_mail_auth_http
- ngx_mail_proxy
- ngx_mail_ssl
- 第三方模塊
- echo-nginx-module #支持在 nginx 配置文件中使用 echo/sleep/time/exec 等類(lèi) Shell 命令
- memc-nginx-module
- rds-json-nginx-module #使 nginx 支持 json 數(shù)據(jù)的處理
- lua-nginx-module
nginx 的 web 請(qǐng)求處理機(jī)制
作為服務(wù)器軟件,必須具備并行處理多個(gè)客戶端的請(qǐng)求的能力, 工作方式主要以下 3 種:
- 多進(jìn)程 (Apache) 優(yōu)點(diǎn):設(shè)計(jì)和實(shí)現(xiàn)簡(jiǎn)單;子進(jìn)程獨(dú)立 缺點(diǎn):生成一個(gè)子進(jìn)程要內(nèi)存復(fù)制,在資源和時(shí)間上造成額外開(kāi)銷(xiāo)
- 多線程 (IIS) 優(yōu)點(diǎn):開(kāi)銷(xiāo)小 缺點(diǎn):開(kāi)發(fā)者自己要對(duì)內(nèi)存進(jìn)行管理;線程之間會(huì)相互影響
- 異步方式 (nginx)
經(jīng)常說(shuō)道異步非阻塞這個(gè)概念, 包含兩層含義:
通信模式: + 同步:發(fā)送方發(fā)送完請(qǐng)求后,等待并接受對(duì)方的回應(yīng)后,再發(fā)送下個(gè)請(qǐng)求 + 異步:發(fā)送方發(fā)送完請(qǐng)求后,不必等待,直接發(fā)送下個(gè)請(qǐng)求
nginx 配置文件實(shí)例
#定義 nginx 運(yùn)行的用戶和用戶組
user www www;
#nginx 進(jìn)程數(shù),建議設(shè)置為等于 CPU 總核心數(shù)。
worker_processes 8;
#nginx 默認(rèn)沒(méi)有開(kāi)啟利用多核 CPU, 通過(guò)增加 worker_cpu_affinity 配置參數(shù)來(lái)充分利用多核 CPU 以下是 8 核的配置參數(shù)
worker_cpu_affinity 00000001 00000010 00000100 00001000 00010000 00100000 01000000 10000000;
#全局錯(cuò)誤日志定義類(lèi)型,[ debug | info | notice | warn | error | crit ]
error_log /var/log/nginx/error.log info;
#進(jìn)程文件
pid /var/run/nginx.pid;
#一個(gè) nginx 進(jìn)程打開(kāi)的最多文件描述符數(shù)目,理論值應(yīng)該是最多打開(kāi)文件數(shù)(系統(tǒng)的值 ulimit -n)與 nginx 進(jìn)程數(shù)相除,但是 nginx 分配請(qǐng)求并不均勻,所以建議與 ulimit -n 的值保持一致。
worker_rlimit_nofile 65535;
#工作模式與連接數(shù)上限
events
{
#參考事件模型,use [ kqueue | rtsig | epoll | /dev/poll | select | poll ]; epoll 模型是 linux 2.6 以上版本內(nèi)核中的高性能網(wǎng)絡(luò) I/O 模型,如果跑在 FreeBSD 上面,就用 kqueue 模型。
#epoll 是多路復(fù)用 IO(I/O Multiplexing) 中的一種方式,但是僅用于 linux2.6 以上內(nèi)核,可以大大提高 nginx 的性能
use epoll;
############################################################################
#單個(gè)后臺(tái) worker process 進(jìn)程的最大并發(fā)鏈接數(shù)
#事件模塊指令,定義 nginx 每個(gè)進(jìn)程最大連接數(shù),默認(rèn) 1024。最大客戶連接數(shù)由 worker_processes 和 worker_connections 決定
#即 max_client=worker_processes*worker_connections, 在作為反向代理時(shí):max_client=worker_processes*worker_connections / 4
worker_connections 65535;
############################################################################
}
#設(shè)定 http 服務(wù)器
http {
include mime.types; #文件擴(kuò)展名與文件類(lèi)型映射表
default_type Application/octet-stream; #默認(rèn)文件類(lèi)型
#charset utf-8; #默認(rèn)編碼
server_names_hash_bucket_size 128; #服務(wù)器名字的 hash 表大小
client_header_buffer_size 32k; #上傳文件大小限制
large_client_header_buffers 4 64k; #設(shè)定請(qǐng)求緩
client_max_body_size 8m; #設(shè)定請(qǐng)求緩
sendfile on; #開(kāi)啟高效文件傳輸模式,sendfile 指令指定 nginx 是否調(diào)用 sendfile 函數(shù)來(lái)輸出文件,對(duì)于普通應(yīng)用設(shè)為 on,如果用來(lái)進(jìn)行下載等應(yīng)用磁盤(pán) IO 重負(fù)載應(yīng)用,可設(shè)置為 off,以平衡磁盤(pán)與網(wǎng)絡(luò) I/O 處理速度,降低系統(tǒng)的負(fù)載。注意:如果圖片顯示不正常把這個(gè)改成 off。
autoindex on; #開(kāi)啟目錄列表訪問(wèn),合適下載服務(wù)器,默認(rèn)關(guān)閉。
tcp_nopush on; #防止網(wǎng)絡(luò)阻塞
tcp_nodelay on; #防止網(wǎng)絡(luò)阻塞
##連接客戶端超時(shí)時(shí)間各種參數(shù)設(shè)置##
keepalive_timeout 120; #單位是秒,客戶端連接時(shí)時(shí)間,超時(shí)之后服務(wù)器端自動(dòng)關(guān)閉該連接 如果 nginx 守護(hù)進(jìn)程在這個(gè)等待的時(shí)間里,一直沒(méi)有收到瀏覽發(fā)過(guò)來(lái) http 請(qǐng)求,則關(guān)閉這個(gè) http 連接
client_header_timeout 10; #客戶端請(qǐng)求頭的超時(shí)時(shí)間
client_body_timeout 10; #客戶端請(qǐng)求主體超時(shí)時(shí)間
reset_timedout_connection on; #告訴 nginx 關(guān)閉不響應(yīng)的客戶端連接。這將會(huì)釋放那個(gè)客戶端所占有的內(nèi)存空間
send_timeout 10; #客戶端響應(yīng)超時(shí)時(shí)間,在兩次客戶端讀取操作之間。如果在這段時(shí)間內(nèi),客戶端沒(méi)有讀取任何數(shù)據(jù),nginx 就會(huì)關(guān)閉連接
################################
#FastCGI 相關(guān)參數(shù)是為了改善網(wǎng)站的性能:減少資源占用,提高訪問(wèn)速度。下面參數(shù)看字面意思都能理解。
fastcgi_connect_timeout 300;
fastcgi_send_timeout 300;
fastcgi_read_timeout 300;
fastcgi_buffer_size 64k;
fastcgi_buffers 4 64k;
fastcgi_busy_buffers_size 128k;
fastcgi_temp_file_write_size 128k;
###作為代理緩存服務(wù)器設(shè)置#######
###先寫(xiě)到 temp 再移動(dòng)到 cache
#proxy_cache_path /var/tmp/nginx/proxy_cache levels=1:2 keys_zone=cache_one:512m inactive=10m max_size=64m;
###以上 proxy_temp 和 proxy_cache 需要在同一個(gè)分區(qū)中
###levels=1:2 表示緩存級(jí)別,表示緩存目錄的第一級(jí)目錄是 1 個(gè)字符,第二級(jí)目錄是 2 個(gè)字符 keys_zone=cache_one:128m 緩存空間起名為 cache_one 大小為 512m
###max_size=64m 表示單個(gè)文件超過(guò) 128m 就不緩存了 inactive=10m 表示緩存的數(shù)據(jù),10 分鐘內(nèi)沒(méi)有被訪問(wèn)過(guò)就刪除
#########end####################
#####對(duì)傳輸文件壓縮###########
#gzip 模塊設(shè)置
gzip on; #開(kāi)啟 gzip 壓縮輸出
gzip_min_length 1k; #最小壓縮文件大小
gzip_buffers 4 16k; #壓縮緩沖區(qū)
gzip_http_version 1.0; #壓縮版本(默認(rèn) 1.1,前端如果是 squid2.5 請(qǐng)使用 1.0)
gzip_comp_level 2; #壓縮等級(jí),gzip 壓縮比,1 為最小,處理最快;9 為壓縮比最大,處理最慢,傳輸速度最快,也最消耗 CPU;
gzip_types text/plain application/x-JAVAscript text/css application/xml;
#壓縮類(lèi)型,默認(rèn)就已經(jīng)包含 text/html,所以下面就不用再寫(xiě)了,寫(xiě)上去也不會(huì)有問(wèn)題,但是會(huì)有一個(gè) warn。
gzip_vary on;
##############################
#limit_zone crawler $binary_remote_addr 10m; #開(kāi)啟限制 IP 連接數(shù)的時(shí)候需要使用
upstream blog.ha97.com {
#upstream 的負(fù)載均衡,weight 是權(quán)重,可以根據(jù)機(jī)器配置定義權(quán)重。weigth 參數(shù)表示權(quán)值,權(quán)值越高被分配到的幾率越大。
server 192.168.80.121:80 weight=3;
server 192.168.80.122:80 weight=2;
server 192.168.80.123:80 weight=3;
}
#虛擬主機(jī)的配置
server {
#監(jiān)聽(tīng)端口
listen 80;
#############https##################
#listen 443 ssl;
#ssl_certificate /opt/https/xxxxxx.crt;
#ssl_certificate_key /opt/https/xxxxxx.key;
#ssl_protocols SSLv3 TLSv1;
#ssl_ciphers HIGH:!ADH:!EXPORT57:RC4+RSA:+MEDIUM;
#ssl_prefer_server_ciphers on;
#ssl_session_cache shared:SSL:2m;
#ssl_session_timeout 5m;
####################################end
#域名可以有多個(gè),用空格隔開(kāi)
server_name www.ha97.com ha97.com;
index index.html index.htm index.php;
root /data/www/ha97;
location ~ .*.(php|php5)?$ {
fastcgi_pass 127.0.0.1:9000;
fastcgi_index index.php;
include fastcgi.conf;
}
#圖片緩存時(shí)間設(shè)置
location ~ .*.(gif|jpg|jpeg|png|bmp|swf)$ {
expires 10d;
}
#JS 和 CSS 緩存時(shí)間設(shè)置
location ~ .*.(js|css)?$ {
expires 1h;
}
#日志格式設(shè)定
log_format access '$remote_addr - $remote_user [$time_local] "$request" ' '$status $body_bytes_sent "$http_referer" ' '"$http_user_agent" $http_x_forwarded_for';
#定義本虛擬主機(jī)的訪問(wèn)日志
access_log /var/log/nginx/ha97access.log access;
#對(duì) "/" 啟用反向代理
location / {
proxy_pass http://127.0.0.1:88;
proxy_redirect off;
proxy_set_header X-Real-IP $remote_addr;
#后端的 Web 服務(wù)器可以通過(guò) X-Forwarded-For 獲取用戶真實(shí) IP
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
#以下是一些反向代理的配置,可選。
proxy_set_header Host $host;
client_max_body_size 10m; #允許客戶端請(qǐng)求的最大單文件字節(jié)數(shù)
client_body_buffer_size 128k; #緩沖區(qū)代理緩沖用戶端請(qǐng)求的最大字節(jié)數(shù),
##代理設(shè)置 以下設(shè)置是 nginx 和后端服務(wù)器之間通訊的設(shè)置##
proxy_connect_timeout 90; #nginx 跟后端服務(wù)器連接超時(shí)時(shí)間(代理連接超時(shí))
proxy_send_timeout 90; #后端服務(wù)器數(shù)據(jù)回傳時(shí)間(代理發(fā)送超時(shí))
proxy_read_timeout 90; #連接成功后,后端服務(wù)器響應(yīng)時(shí)間(代理接收超時(shí))
proxy_buffering on; #該指令開(kāi)啟從后端被代理服務(wù)器的響應(yīng)內(nèi)容緩沖 此參數(shù)開(kāi)啟后 proxy_buffers 和 proxy_busy_buffers_size 參數(shù)才會(huì)起作用
proxy_buffer_size 4k; #設(shè)置代理服務(wù)器(nginx)保存用戶頭信息的緩沖區(qū)大小
proxy_buffers 4 32k; #proxy_buffers 緩沖區(qū),網(wǎng)頁(yè)平均在 32k 以下的設(shè)置
proxy_busy_buffers_size 64k; #高負(fù)荷下緩沖大?。╬roxy_buffers*2)
proxy_max_temp_file_size 2048m; #默認(rèn) 1024m, 該指令用于設(shè)置當(dāng)網(wǎng)頁(yè)內(nèi)容大于 proxy_buffers 時(shí),臨時(shí)文件大小的最大值。如果文件大于這個(gè)值,它將從 upstream 服務(wù)器同步地傳遞請(qǐng)求,而不是緩沖到磁盤(pán)
proxy_temp_file_write_size 512k; 這是當(dāng)被代理服務(wù)器的響應(yīng)過(guò)大時(shí) nginx 一次性寫(xiě)入臨時(shí)文件的數(shù)據(jù)量。
proxy_temp_path /var/tmp/nginx/proxy_temp; ##定義緩沖存儲(chǔ)目錄,之前必須要先手動(dòng)創(chuàng)建此目錄
proxy_headers_hash_max_size 51200;
proxy_headers_hash_bucket_size 6400;
#######################################################
}
#設(shè)定查看 nginx 狀態(tài)的地址
location /nginxStatus {
stub_status on;
access_log on;
auth_basic "nginxStatus";
auth_basic_user_file conf/htpasswd;
#htpasswd 文件的內(nèi)容可以用 apache 提供的 htpasswd 工具來(lái)產(chǎn)生。
}
#本地動(dòng)靜分離反向代理配置
#所有 jsp 的頁(yè)面均交由 Tomcat 或 resin 處理
location ~ .(jsp|jspx|do)?$ {
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://127.0.0.1:8080;
}
#所有靜態(tài)文件由 nginx 直接讀取不經(jīng)過(guò) tomcat 或 resin
location ~ .*.(htm|html|gif|jpg|jpeg|png|bmp|swf|ioc|rar|zip|txt|flv|mid|doc|ppt|pdf|xls|mp3|wma)$
{ expires 15d; }
location ~ .*.(js|css)?$
{ expires 1h; }
}
}
復(fù)制代碼
nginx 服務(wù)器基礎(chǔ)配置指令
nginx.conf 文件的結(jié)構(gòu)
- Global: nginx 運(yùn)行相關(guān)
- events: 與用戶的網(wǎng)絡(luò)連接相關(guān)
- http http Global: 代理,緩存,日志,以及第三方模塊的配置 server server Global: 虛擬主機(jī)相關(guān) location: 地址定向,數(shù)據(jù)緩存,應(yīng)答控制,以及第三方模塊的配置
所有的所有的所有的指令,都要以;結(jié)尾
nginx 運(yùn)行相關(guān)的 Global 部分
配置運(yùn)行 nginx 服務(wù)器用戶
user nobody nobody;
配置允許生成的 worker process 數(shù)
worker_processes auto; worker_processes 4;
這個(gè)數(shù)字,跟電腦 CPU 核數(shù)要保持一致
# grep ^proces /proc/cpuinfo
processor : 0
processor : 1
processor : 2
processor : 3
# grep ^proces /proc/cpuinfo | wc -l
4
復(fù)制代碼
配置 nginx 進(jìn)程 PID 存放路徑
pid logs/nginx.pid;
這里面保存的就是一個(gè)數(shù)字,nginx master 進(jìn)程的進(jìn)程號(hào)
配置錯(cuò)誤日志的存放路徑
error_log logs/error.log; error_log logs/error.log error;
配置文件的引入
include mime.types; include fastcgi_params; include ../../conf/*.conf;
與用戶的網(wǎng)絡(luò)連接相關(guān)的 events
設(shè)置網(wǎng)絡(luò)連接的序列化
accept_mutex on;
對(duì)多個(gè) nginx 進(jìn)程接收連接進(jìn)行序列化,防止多個(gè)進(jìn)程對(duì)連接的爭(zhēng)搶(驚群)
設(shè)置是否允許同時(shí)接收多個(gè)網(wǎng)絡(luò)連接
multi_accept off;
事件驅(qū)動(dòng)模型的選擇
use select|poll|kqueue|epoll|rtsig|/dev/poll|eventport
這個(gè)重點(diǎn),后面再看
配置最大連接數(shù)
worker_connections 512;
http
http Global 代理 - 緩存 - 日志 - 第三方模塊配置
定義 MIME-Type
include mime.types; default_type application/octet-stream;
自定義服務(wù)日志
access_log logs/access.log main; access_log off;
配置允許 sendfile 方式傳輸文件
sendfile off;
sendfile on; sendfile_max_chunk 128k;
nginx 每個(gè) worker process 每次調(diào)用 sendfile() 傳輸?shù)臄?shù)據(jù)量的最大值
Refer:
配置連接超時(shí)時(shí)間
與用戶建立連接后,nginx 可以保持這些連接一段時(shí)間,默認(rèn) 75s 下面的 65s 可以被 Mozilla/Konqueror 識(shí)別,是發(fā)給用戶端的頭部信息Keep-Alive值
keepalive_timeout 75s 65s;
單連接請(qǐng)求數(shù)上限
和用戶端建立連接后,用戶通過(guò)此連接發(fā)送請(qǐng)求;這條指令用于設(shè)置請(qǐng)求的上限數(shù)
keepalive_requests 100;
server
配置網(wǎng)絡(luò)監(jiān)聽(tīng)
listen *:80 | *:8000; # 監(jiān)聽(tīng)所有的 80 和 8000 端口
listen 192.168.1.10:8000; listen 192.168.1.10; listen 8000; # 等同于 listen *:8000; listen 192.168.1.10 default_server backlog=511; # 該 ip 的連接請(qǐng)求默認(rèn)由此虛擬主機(jī)處理;最多允許 1024 個(gè)網(wǎng)絡(luò)連接同時(shí)處于掛起狀態(tài)
基于名稱的虛擬主機(jī)配置
server_name myserver.com www.myserver.com;
server_name .myserver.com www.myserver. myserver2.*; # 使用通配符
不允許的情況: server_name www.ab*d.com; # *只允許出現(xiàn)在 www 和 com 的位置
server_name ~^wwwd+.myserver.com$; # 使用正則
nginx 的配置中,可以用正則的地方,都以~開(kāi)頭
from nginx~0.7.40 開(kāi)始,server_name 中的正則支持 字符串捕獲功能(capture)
server_name ~^www.(.+).com$; # 當(dāng)請(qǐng)求通過(guò) www.myserver.com 請(qǐng)求時(shí), myserver 就被記錄到$1中,在本 server 的上下文中就可以使用
如果一個(gè)名稱 被多個(gè)虛擬主機(jī)的 server_name 匹配成功,那這個(gè)請(qǐng)求到底交給誰(shuí)處理呢?看優(yōu)先級(jí):
- 準(zhǔn)確匹配到 server_name
- 通配符在開(kāi)始時(shí)匹配到 server_name
- 通配符在結(jié)尾時(shí)匹配到 server_name
- 正則表達(dá)式匹配 server_name
- 先到先得
配置 https 證書(shū)
原理
https 是在 http 和 TCP 中間加上一層加密層
瀏覽器向服務(wù)端發(fā)送消息時(shí):本質(zhì)上是瀏覽器(客戶端)使用服務(wù)端的公鑰來(lái)加密信息,服務(wù)端使用自己的私鑰解密, 瀏覽器從服務(wù)端獲取消息是:服務(wù)端使用自己私鑰加密,瀏覽器(客戶端)使用服務(wù)端的公鑰來(lái)解密信息
在這個(gè)過(guò)程中,需要保證服務(wù)端給瀏覽器的公鑰不是假冒的。證明服務(wù)端公鑰信息的機(jī)構(gòu)是 CA(數(shù)字認(rèn)證中心)
可以理解為:如果想證明一個(gè)人的身份是真的,就得證明這個(gè)人的身份證是真的
數(shù)字證書(shū)
數(shù)字證書(shū)相當(dāng)于物理世界中的身份證,
在網(wǎng)絡(luò)中傳遞信息的雙方互相不能見(jiàn)面,利用數(shù)字證書(shū)可確認(rèn)雙方身份,而不是他人冒充的。
這個(gè)數(shù)字證書(shū)由信任的第三方,即認(rèn)證中心使用自己的私鑰對(duì) A 的公鑰加密,加密后文件就是網(wǎng)絡(luò)上的身份證了,即數(shù)字證書(shū)
復(fù)制代碼
大致可以理解為如下
1. 服務(wù)端將自己的公鑰和其他信息(服務(wù)端數(shù)字證書(shū)),請(qǐng)求數(shù)字認(rèn)證中心簽名,數(shù)字認(rèn)證中心使用自己的私鑰在證書(shū)里加密(只有數(shù)字認(rèn)證中心的公鑰才能解開(kāi))
2. 服務(wù)端將自己的證書(shū)(證書(shū)里面包括服務(wù)端的公鑰)給瀏覽器
3. 瀏覽器的“證書(shū)管理器”中有“受信任的根證書(shū)頒發(fā)機(jī)構(gòu)”列表,客戶端在接收到響應(yīng)后,會(huì)在這個(gè)列表里查看是否存在解開(kāi)該服務(wù)器數(shù)字證書(shū)的公鑰。有兩種錯(cuò)誤情況:如果公鑰在這個(gè)列表里,但是解碼后的內(nèi)容不匹配,說(shuō)明證書(shū)被冒用;如果公鑰不在這個(gè)列表里,說(shuō)明這張證書(shū)不是受信任的機(jī)構(gòu)所頒發(fā),他的真實(shí)性無(wú)法確定
4. 如果一切都沒(méi)問(wèn)題,瀏覽器就可以使用服務(wù)器的公鑰對(duì)信息內(nèi)容進(jìn)行加密,然后與服務(wù)器交換信息(已加密)
+--------------+ +------------------+
| 服務(wù)端 |---------->| 數(shù)字認(rèn)證中心 (CA) |
+------+-------+ 1 X +------------------+
| / /
| / /
| / /
| / /
|2 3 / / 4
| / /
| / /
| / /
X / /
+--------------+ /
| 瀏覽器 |X
+--------------+
只要證書(shū)(證書(shū)里有服務(wù)端的公鑰)是可信的,公鑰就是可信的。
證書(shū)格式
Linux 下的工具們通常使用 base64 編碼的文本格式,相關(guān)常用后綴如下
- 證書(shū) .crt .pem .cer(IIS 等一些平臺(tái)下,則習(xí)慣用 cer 作為證書(shū)文件的擴(kuò)展名,二進(jìn)制證書(shū))
- 私鑰:.key
- 證書(shū)請(qǐng)求:.csr
- 其他 .keystore java 密鑰庫(kù)(包括證書(shū)和私鑰)
制作證書(shū)
1. 生成服務(wù)器端的私鑰 (key 文件)
$openssl genrsa -out server.key 1024
2. 生成服務(wù)器端證書(shū)簽名請(qǐng)求文件 (csr 文件);
$ openssl req -new -key server.key -out server.csr
...
Country Name:CN------------ 證書(shū)持有者所在國(guó)家
State or Province Name:BJ-- 證書(shū)持有者所在州或省份(可省略不填)
Locality Name:BJ----------- 證書(shū)持有者所在城市(可省略不填)
Organization Name:SC------- 證書(shū)持有者所屬組織或公司
Organizational Unit Name:.- 證書(shū)持有者所屬部門(mén)(可省略不填)
Common Name :ceshi.com----- 域名
Email Address:------------- 郵箱(可省略不填)
A challenge password:------ 直接回車(chē)
An optional company name:-- 直接回車(chē)
3. 生成證書(shū)文件 (crt 文件)
$ openssl x509 -req -days 1000 -in server.csr -signkey server.key -out server.crt
復(fù)制代碼
以上生成 server.crt server.key 文件即是用于 HTTPS 配置的證書(shū)和 key
如果想查看證書(shū)里面的內(nèi)容,可以通過(guò) $openssl x509 -in server.crt -text -noout 查看
配置 nginx
在 nginx 的 server 區(qū)域內(nèi)添加如下
listen 443 ssl;
ssl_certificate /opt/https/server.crt;
ssl_certificate_key /opt/https/server.key;
ssl_protocols SSLv3 TLSv1;
ssl_ciphers HIGH:!ADH:!EXPORT57:RC4+RSA:+MEDIUM;
ssl_prefer_server_ciphers on;
ssl_session_cache shared:SSL:2m;
ssl_session_timeout 5m;
復(fù)制代碼
基于 IP 的虛擬主機(jī)配置
基于 IP 的虛擬主機(jī),需要將網(wǎng)卡設(shè)置為同時(shí)能夠監(jiān)聽(tīng)多個(gè) IP 地址
ifconfig
# 查看到本機(jī) IP 地址為 192.168.1.30
ifconfig eth1:0 192.168.1.31 netmask 255.255.255.0 up
ifconfig eth1:1 192.168.1.32 netmask 255.255.255.0 up
ifconfig
# 這時(shí)就看到 eth1 增加來(lái) 2 個(gè)別名, eth1:0 eth1:1
# 如果需要機(jī)器重啟后仍保持這兩個(gè)虛擬的 IP
echo "ifconfig eth1:0 192.168.1.31 netmask 255.255.255.0 up" >> /etc/rc.local
echo "ifconfig eth1:0 192.168.1.32 netmask 255.255.255.0 up" >> /etc/rc.local
復(fù)制代碼
再來(lái)配置基于 IP 的虛擬主機(jī)
http {
...
server {
listen 80;
server_name 192.168.1.31;
...
}
server {
listen 80;
server_name 192.168.1.32;
...
}
}
復(fù)制代碼
配置 location 塊
location 塊的配置,應(yīng)該是最常用的了
location [ = | ~ | ~* | ^~ ] uri {...}
這里內(nèi)容分 2 塊,匹配方式和 uri, 其中 uri 又分為 標(biāo)準(zhǔn) uri 和正則 uri
先不考慮 那 4 種匹配方式
- nginx 首先會(huì)再 server 塊的多個(gè) location 中搜索是否有標(biāo)準(zhǔn) uri和請(qǐng)求字符串匹配, 如果有,記錄匹配度最高的一個(gè);
- 然后,再用 location 塊中的正則 uri和請(qǐng)求字符串匹配, 當(dāng)?shù)谝粋€(gè)正則 uri匹配成功,即停止搜索, 并使用該 location 塊處理請(qǐng)求;
- 如果,所有的正則 uri都匹配失敗,就使用剛記錄下的匹配度最高的一個(gè)標(biāo)準(zhǔn) uri處理請(qǐng)求
- 如果都失敗了,那就失敗嘍
再看 4 種匹配方式:
- =: 用于標(biāo)準(zhǔn) uri前,要求請(qǐng)求字符串與其嚴(yán)格匹配,成功則立即處理
- ^~: 用于標(biāo)準(zhǔn) uri前,并要求一旦匹配到,立即處理,不再去匹配其他的那些個(gè)正則 uri
- ~: 用于正則 uri前,表示 uri 包含正則表達(dá)式, 并區(qū)分大小寫(xiě)
- ~*: 用于正則 uri前, 表示 uri 包含正則表達(dá)式, 不區(qū)分大小寫(xiě)
^~ 也是支持瀏覽器編碼過(guò)的 URI 的匹配的哦, 如 /html/%20/data 可以成功匹配 /html/ /data
[root] 配置請(qǐng)求的根目錄
Web 服務(wù)器收到請(qǐng)求后,首先要在服務(wù)端指定的目錄中尋找請(qǐng)求資源
root /var/www;
復(fù)制代碼
root 后跟的指定目錄是上級(jí)目錄
該上級(jí)目錄下要含有和 location 后指定名稱的同名目錄才行,末尾“/”加不加無(wú)所謂
location /c/ {
root /a/
}
復(fù)制代碼
訪問(wèn)站點(diǎn) http://location/c 訪問(wèn)的就是 /a/c 目錄下的站點(diǎn)信息。
[alias] 更改 location 的 URI
除了使用 root 指明處理請(qǐng)求的根目錄,還可以使用 alias 改變 location 收到的 URI 的請(qǐng)求路徑
location ~ ^/data/(.+.(htm|html))$ {
alias /locatinotest1/other/$1;
}
復(fù)制代碼
alias 后跟的指定目錄是準(zhǔn)確的,并且末尾必須加“/”,否則找不到文件
location /c/ {
alias /a/
}
【注】一般情況下,在 location / 中配置 root,在 location /other 中配置 alias 是一個(gè)好習(xí)慣。
設(shè)置網(wǎng)站的默認(rèn)首頁(yè)
index 指令主要有 2 個(gè)作用:
- 對(duì)請(qǐng)求地址沒(méi)有指明首頁(yè)的,指定默認(rèn)首頁(yè)
- 對(duì)一個(gè)請(qǐng)求,根據(jù)請(qǐng)求內(nèi)容而設(shè)置不同的首頁(yè),如下:
location ~ ^/data/(.+)/web/$ {
index index.$1.html index.htm;
}
復(fù)制代碼
設(shè)置網(wǎng)站的錯(cuò)誤頁(yè)面
error_page 404 /404.html; error_page 403 /forbidden.html; error_page 404 =301 /404.html;
location /404.html {
root /myserver/errorpages/;
}
復(fù)制代碼
基于 IP 配置 nginx 的訪問(wèn)權(quán)限
location / {
deny 192.168.1.1;
allow 192.168.1.0/24;
allow 192.168.1.2/24;
deny all;
}
復(fù)制代碼
從 192.168.1.0 的用戶時(shí)可以訪問(wèn)的,因?yàn)榻馕龅?allow 那一行之后就停止解析了
基于密碼配置 nginx 的訪問(wèn)權(quán)限
auth_basic "please login"; auth_basic_user_file /etc/nginx/conf/pass_file;
這里的 file 必須使用絕對(duì)路徑,使用相對(duì)路徑無(wú)效
# /usr/local/apache2/bin/htpasswd -c -d pass_file user_name
# 回車(chē)輸入密碼,-c 表示生成文件,-d 是以 crypt 加密。
name1:password1
name2:password2:comment
應(yīng)用
架設(shè)簡(jiǎn)單文件服務(wù)器
將 /data/public/ 目錄下的文件通過(guò) nginx 提供給外部訪問(wèn)
#mkdir /data/public/
#chmod 777 /data/public/
復(fù)制代碼
worker_processes 1;
error_log logs/error.log info;
events {
use epoll;
}
http {
server {
# 監(jiān)聽(tīng) 8080 端口
listen 8080;
location /share/ {
# 打開(kāi)自動(dòng)列表功能,通常關(guān)閉
autoindex on;
# 將 /share/ 路徑映射至 /data/public/,請(qǐng)保證 nginx 進(jìn)程有權(quán)限訪問(wèn) /data/public/
alias /data/public/;
}
}
}
復(fù)制代碼
nginx 正向代理
- 正向代理指代理客戶端訪問(wèn)服務(wù)器的一個(gè)中介服務(wù)器,代理的對(duì)象是客戶端。正向代理就是代理服務(wù)器替客戶端去訪問(wèn)目標(biāo)服務(wù)器
- 反向代理指代理后端服務(wù)器響應(yīng)客戶端請(qǐng)求的一個(gè)中介服務(wù)器,代理的對(duì)象是服務(wù)器。
- 配置
代理服務(wù)器配置
nginx.conf
server{
resolver x.x.x.x;
# resolver 8.8.8.8;
listen 82;
location / {
proxy_pass http://$http_host$request_uri;
}
access_log /data/httplogs/proxy-$host-aceess.log;
}
復(fù)制代碼
location 保持原樣即可,根據(jù)自己的配置更改 listen port 和 dnf 即 resolver 驗(yàn)證: 在需要訪問(wèn)外網(wǎng)的機(jī)器上執(zhí)行以下操作之一即可:
1. export http_proxy=http://yourproxyaddress:proxyport(建議)
2. vim ~/.bashrc
export http_proxy=http://yourproxyaddress:proxyport
復(fù)制代碼
2 不足 nginx 不支持 CONNECT 方法,不像我們平時(shí)用的 GET 或者 POST,可以選用 apache 或 squid 作為代替方案。
nginx 服務(wù)器基礎(chǔ)配置實(shí)例
user nginx nginx;
worker_processes 3;
error_log logs/error.log;
pid myweb/nginx.pid;
events {
use epoll;
worker_connections 1024;
}
http {
include mime.types;
default_type applicatioin/octet-stream;
sendfile on;
keepalive_timeout 65;
log_format access.log '$remote_addr [$time_local] "$request" "$http_user_agent"';
server {
listen 8081;
server_name myServer1;
access_log myweb/server1/log/access.log;
error_page 404 /404.html;
location /server1/location1 {
root myweb;
index index.svr1-loc1.htm;
}
location /server1/location2 {
root myweb;
index index.svr1-loc2.htm;
}
}
server {
listen 8082;
server_name 192.168.0.254;
auth_basic "please Login:";
auth_basic_user_file /opt/X_nginx/nginx/myweb/user_passwd;
access_log myweb/server2/log/access.log;
error_page 404 /404.html;
location /server2/location1 {
root myweb;
index index.svr2-loc1.htm;
}
location /svr2/loc2 {
alias myweb/server2/location2/;
index index.svr2-loc2.htm;
}
location = /404.html {
root myweb/;
index 404.html;
}
}
}
復(fù)制代碼
#./sbin/nginx -c conf/nginx02.conf
nginx: [warn] the "user" directive makes sense only if the master process runs with super-user privileges, ignored in /opt/X_nginx/nginx/conf/nginx02.conf:1
.
├── 404.html
├── server1
│ ├── location1
│ │ └── index.svr1-loc1.htm
│ ├── location2
│ │ └── index.svr1-loc2.htm
│ └── log
│ └── access.log
└── server2
├── location1
│ └── index.svr2-loc1.htm
├── location2
│ └── index.svr2-loc2.htm
└── log
└── access.log
8 directories, 7 files
復(fù)制代碼
測(cè)試 myServer1 的訪問(wèn)
http://myserver1:8081/server1/location1/
this is server1/location1/index.svr1-loc1.htm
http://myserver1:8081/server1/location2/
this is server1/location1/index.svr1-loc2.htm
復(fù)制代碼
測(cè)試 myServer2 的訪問(wèn)
http://192.168.0.254:8082/server2/location1/
this is server2/location1/index.svr2-loc1.htm
http://192.168.0.254:8082/svr2/loc2/
this is server2/location1/index.svr2-loc2.htm
http://192.168.0.254:8082/server2/location2/
404 404 404 404
復(fù)制代碼
使用緩存
創(chuàng)建緩存目錄
mkdir /tmp/nginx_proxy_cache2
chmod 777 /tmp/nginx_proxy_cache2
復(fù)制代碼
修改配置文件
# http 區(qū)域下添加緩存區(qū)配置
proxy_cache_path /tmp/nginx_proxy_cache2 levels=1 keys_zone=cache_one:512m inactive=60s max_size=1000m;
# server 區(qū)域下添加緩存配置
#緩存相應(yīng)的文件(靜態(tài)文件)
location ~ .(gif|jpg|png|htm|html|css|js|flv|ico|swf)(.*) {
proxy_pass http://IP: 端口;#如果沒(méi)有緩存則通過(guò) proxy_pass 轉(zhuǎn)向請(qǐng)求
proxy_redirect off;
proxy_set_header Host $host;
proxy_cache cache_one;
proxy_cache_valid 200 302 1h; #對(duì)不同的 HTTP 狀態(tài)碼設(shè)置不同的緩存時(shí)間,h 小時(shí),d 天數(shù)
proxy_cache_valid 301 1d;
proxy_cache_valid any 1m;
expires 30d;
}
復(fù)制代碼
使用 location 反向代理到已有網(wǎng)站
location ~/bianque/(.*)$ {
proxy_pass http://127.0.0.1:8888/$1/?$args;
}
復(fù)制代碼
加內(nèi)置變量 args`是非必須的 $1 取自正則表達(dá)式部分()里的內(nèi)容
其他
ngx_http_sub_module 替換響應(yīng)中內(nèi)容
- ngx_http_sub_module nginx 用來(lái)替換響應(yīng)內(nèi)容的一個(gè)模塊(應(yīng)用:有些程序中寫(xiě)死了端口,可以通過(guò)此工具將頁(yè)面中的端口替換為其他端口)
配置 http 強(qiáng)制跳轉(zhuǎn) https
在 nginx 配置文件中的 server 區(qū)域添加如下內(nèi)容
if ($scheme = 'http') {
rewrite ^(.*)$ https://$host$uri;
}