nginx 這一篇就夠了

nginx 這一篇就夠了

nginx

安裝

安裝依賴

安裝 nginx 之前,確保系統已經安裝 gcc、openssl-devel、pcre-devel 和 zlib-devel 軟件庫

  • gcc 可以通過光盤直接選擇安裝
  • openssl-devel、zlib-devel 可以通過光盤直接選擇安裝,https 時使用
  • pcre-devel 安裝 pcre 庫是爲了使 nginx 支持 HTTP Rewrite 模塊

下載

nginx 下載

編譯安裝

通過上面的下載頁下載最新的穩定版

#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 服務器的開發完全遵循模塊化設計思想

模塊化開發

  1. 單一職責原則,一個模塊只負責一個功能
  2. 將程序分解,自頂向下,逐步求精
  3. 高內聚,低耦合

nginx 的模塊化結構

  • 核心模塊:nginx 最基本最核心的服務,如進程管理、權限控制、日誌記錄;
  • 標準 HTTP 模塊:nginx 服務器的標準 HTTP 功能;
  • 可選 HTTP 模塊:處理特殊的 HTTP 請求
  • 郵件服務模塊:郵件服務
  • 第三方模塊:作爲擴展,完成特殊功能

nginx 的模塊清單

  • 核心模塊

    • ngx_core
    • ngx_errlog
    • ngx_conf
    • ngx_events
    • ngx_event_core
    • ngx_epll
    • ngx_regex
  • 標準 HTTP 模塊

    • 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 模塊

    • 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 進行轉換
  • 郵件服務模塊

    • 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 等類 Shell 命令
    • memc-nginx-module
    • rds-json-nginx-module #使 nginx 支持 json 數據的處理
    • lua-nginx-module

nginx 的 web 請求處理機制

作爲服務器軟件,必須具備並行處理多個客戶端的請求的能力, 工作方式主要以下 3 種:

  • 多進程 (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 匹配成功,那這個請求到底交給誰處理呢?看優先級:

  1. 準確匹配到 server_name
  2. 通配符在開始時匹配到 server_name
  3. 通配符在結尾時匹配到 server_name
  4. 正則表達式匹配 server_name
  5. 先到先得

配置 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 種匹配方式

  1. nginx 首先會再 server 塊的多個 location 中搜索是否有標準 uri和請求字符串匹配, 如果有,記錄匹配度最高的一個;
  2. 然後,再用 location 塊中的正則 uri和請求字符串匹配, 當第一個正則 uri匹配成功,即停止搜索, 並使用該 location 塊處理請求;
  3. 如果,所有的正則 uri都匹配失敗,就使用剛記錄下的匹配度最高的一個標準 uri處理請求
  4. 如果都失敗了,那就失敗嘍

再看 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 正向代理

  • 正向代理指代理客戶端訪問服務器的一箇中介服務器,代理的對象是客戶端。正向代理就是代理服務器替客戶端去訪問目標服務器
  • 反向代理指代理後端服務器響應客戶端請求的一箇中介服務器,代理的對象是服務器。
  1. 配置

代理服務器配置

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 是保障 nginx 正則捕獲 get 請求時不丟失,如果只是 post 請求,`args`是非必須的
  • $1 取自正則表達式部分()裏的內容

其他

ngx_http_sub_module 替換響應中內容

  • ngx_http_sub_module nginx 用來替換響應內容的一個模塊(應用:有些程序中寫死了端口,可以通過此工具將頁面中的端口替換爲其他端口)

配置 http 強制跳轉 https

在 nginx 配置文件中的 server 區域添加如下內容

if ($scheme = 'http') {
    rewrite ^(.*)$ https://$host$uri;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章