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