Nginx反向代理

什麼是反向代理

當咱們有一個服務器集羣,而且服務器集羣中的每臺服務器的內容同樣的時候,一樣咱們要直接從我的電腦訪問到服務器集羣服務器的時候沒法訪問,必須經過第三方服務器才能訪問集羣javascript

這個時候,咱們經過第三方服務器訪問服務器集羣的內容,可是咱們並不知道是哪一臺服務器提供的內容,此種代理方式稱爲反向代理。php

image.png

image.png

反向代理優勢

保護網站安全,全部請求都先通過代理服務器。css

負載均衡,把請求轉發到壓力較小的服務器。html

能夠作一些中間層設置,好比緩存靜態資源java

Nginx基礎

命令

nginx目錄node

nginx -t // 顯示nginx配置信息
cd /usr/local/etc/nginx
複製代碼

啓動nginxlinux

nginx // 默認8080端口啓動成功,可訪問http://localhost:8080/
servive nginx start // ubantu下
複製代碼

關閉nginxnginx

nginx -s stop
servive nginx stop // ubantu下
複製代碼

重啓nginxgit

nginx -s reload // 每次修改完nginx.conf文件就須要重啓nginx
servive nginx restart // ubantu下
複製代碼

Nginx配置

瞭解Nginx配置

先看個簡單的案例瞭解下nginx配置:github

########### 每一個指令必須有分號結束。#################
http {
    access_log /var/logs/nginx-access.log; # 記錄日誌地址
    # 日誌格式
    log_format combined '$remote_addr - $remote_user [$time_local] '
                    '"$request" $status $body_bytes_sent '
                    '"$http_referer" "$http_user_agent"';

    # 能夠有多個server
    server {
        listen 8080; #監聽HTTP端口
        server_name 127.0.0.1; #監聽地址 
        root /data/up1; # server根目錄。未設置時,MacOS默認是/usr/local/var/www

        location / {
            proxy_pass http://localhost:8080; # 代理
        }

        location /images/ {
            root /data; # 設置該路徑下的根目錄(覆蓋server根目錄)
        }

        # 接口
        location = /logout {
            default_type application/json;
            add_header Cache-Control no-cache;
            add_header Access-Control-Allow-Origin *;
            return 200 '{"code":200}';
        }

        location ~ /\.ht {  #禁止訪問 .htxxx 文件
           deny all;
        }
        location = /do_not_delete.html { #直接簡單粗暴的返回狀態碼及內容文本
           return 200 "hello.";
        }
    }
}
複製代碼

location配置

重點看下location配置

語法規則: location [=|~|~*|^~] /uri/ { … }

  • = 開頭表示精確匹配
  • ~ 開頭表示區分大小寫的正則匹配
  • ~* 開頭表示不區分大小寫的正則匹配
  • ^~ 開頭表示uri以某個常規字符串開頭
server {
    listen 80; # 監聽80端口

    # http://localhost/some/example.html訪問/data/www/some/example.html
    location / {
        root /data/www;
    }

    # http://localhost/images/index.html訪問/data/images/index.html
    # 注意:這裏不是訪問/data/index.html
    location /images/ {
        root /data;
    }

    # http://localhost/images/example.png訪問/data/images/example.png
    location ~ \.(gif|jpg|png)$ {
        root /data/images;
    }
}
複製代碼

負載均衡(反向代理)

用戶輸入http://test-openai.com 時,訪問80端口 nginx監聽到80端口被訪問,匹配到的/路徑,被反向代理到http://dramatic-offical-website dramatic-offical-website集羣管理着一堆機器地址,從而實現負載均衡。 若是匹配到http://test-openai.com/images/ 路徑,則直接映射/data下的文件

# 虛擬主機配置
server {
    server_name test-openai.com; # 請求到達的服務器名,定義使用test-openai.com訪問,
    listen 80; # 監聽80端口
    listen 443 ssl; # https默認端口是443

    # 對 / 全部作負載均衡+反向代理
    location / {
        proxy_pass http://dramatic-offical-website; # 代理到目標地址
    }

    # 靜態文件,nginx本身處理
    location /images/ {
        root /data; # 映射到/data/images
    }
}

# 設定負載均衡後臺服務器列表
upstream dramatic-offical-website {
    server 10.192.106.133;
    server 10.192.106.134;
}
複製代碼

nginx.conf 配置文件全解析

#運行用戶
#user somebody;

#啓動進程,一般設置成和cpu的數量相等
worker_processes  1;

#全局錯誤日誌
error_log  D:/Tools/nginx-1.10.1/logs/error.log;
error_log  D:/Tools/nginx-1.10.1/logs/notice.log  notice;
error_log  D:/Tools/nginx-1.10.1/logs/info.log  info;

#PID文件,記錄當前啓動的nginx的進程ID
pid        D:/Tools/nginx-1.10.1/logs/nginx.pid;

#工做模式及鏈接數上限
events {
    worker_connections 1024;    #單個後臺worker process進程的最大併發連接數
}

#設定http服務器,利用它的反向代理功能提供負載均衡支持
http {
    #設定mime類型(郵件支持類型),類型由mime.types文件定義
    include       D:/Tools/nginx-1.10.1/conf/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    D:/Tools/nginx-1.10.1/logs/access.log main;
    rewrite_log     on;

    #sendfile 指令指定 nginx 是否調用 sendfile 函數(zero copy 方式)來輸出文件,對於普通應用,
    #必須設爲 on,若是用來進行下載等應用磁盤IO重負載應用,可設置爲 off,以平衡磁盤與網絡I/O處理速度,下降系統的uptime.
    sendfile        on;
    #tcp_nopush on;

    #鏈接超時時間
    keepalive_timeout  120;
    tcp_nodelay        on;

    #gzip壓縮開關
    #gzip on;

    #設定實際的服務器列表
    upstream zp_server1{
        server 127.0.0.1:8089;
    }

    #HTTP服務器
    server {
        #監聽80端口,80端口是知名端口號,用於HTTP協議
        listen       80;

        #定義使用www.xx.com訪問
        server_name  www.helloworld.com;

        #首頁
        index index.html

        #指向webapp的目錄
        root D:\01_Workspace\Project\github\zp\SpringNotes\spring-security\spring-shiro\src\main\webapp;

        #編碼格式
        charset utf-8;

        #代理配置參數
        proxy_connect_timeout 180;
        proxy_send_timeout 180;
        proxy_read_timeout 180;
        proxy_set_header Host $host;
        proxy_set_header X-Forwarder-For $remote_addr;

        #反向代理的路徑(和upstream綁定),location 後面設置映射的路徑
        location / {
            proxy_pass http://zp_server1;
        }

        #靜態文件,nginx本身處理
        location ~ ^/(images|javascript|js|css|flash|media|static)/ {
            root D:\01_Workspace\Project\github\zp\SpringNotes\spring-security\spring-shiro\src\main\webapp\views;
            #過時30天,靜態文件不怎麼更新,過時能夠設大一點,若是頻繁更新,則能夠設置得小一點。
            expires 30d;
        }

        #設定查看Nginx狀態的地址
        location /NginxStatus {
            stub_status           on;
            access_log            on;
            auth_basic            "NginxStatus";
            auth_basic_user_file  conf/htpasswd;
        }

        #禁止訪問 .htxxx 文件
        location ~ /\.ht {
            deny all;
        }

        #錯誤處理頁面(可選擇性配置)
        #error_page 404 /404.html;
        #error_page 500 502 503 504 /50x.html;
        #location = /50x.html {
        # root html;
        #}
    }
}
複製代碼

內置全局變量:

$args :這個變量等於請求行中的參數,同$query_string
$content_length : 請求頭中的Content-length字段。
$content_type : 請求頭中的Content-Type字段。
$document_root : 當前請求在root指令中指定的值。
$host : 請求主機頭字段,不然爲服務器名稱。
$http_user_agent : 客戶端agent信息
$http_cookie : 客戶端cookie信息
$limit_rate : 這個變量能夠限制鏈接速率。
$request_method : 客戶端請求的動做,一般爲GET或POST。
$remote_addr : 客戶端的IP地址。
$remote_port : 客戶端的端口。
$remote_user : 已經通過Auth Basic Module驗證的用戶名。
$request_filename : 當前請求的文件路徑,由root或alias指令與URI請求生成。
$scheme : HTTP方法(如http,https)。
$server_protocol : 請求使用的協議,一般是HTTP/1.0或HTTP/1.1。
$server_addr : 服務器地址,在完成一次系統調用後能夠肯定這個值。
$server_name : 服務器名稱。
$server_port : 請求到達服務器的端口號。
$request_uri : 包含請求參數的原始URI,不包含主機名,如:」/foo/bar.php?arg=baz」。
$uri : 不帶請求參數的當前URI,$uri不包含主機名,如」/foo/bar.html」。
$document_uri : 與$uri相同。
複製代碼

總結技巧

防盜鏈

location ~* \.(gif|jpg|swf)$ {
    valid_referers none blocked start.igrow.cn sta.igrow.cn;
    if ($invalid_referer) {
        rewrite ^/ http://$host/logo.png;
    }
}
複製代碼

根據文件類型設置過時時間

location ~* \.(js|css|jpg|jpeg|gif|png|swf)$ {
    if (-f $request_filename) {
        expires 1h;
        break;
    }
}
複製代碼

禁止訪問某個目錄

location ~* \.(txt|doc)${ root /data/www/wwwroot/linuxtone/test; deny all; }
複製代碼

gzip

#gzip on|off
gzip  on;

#消息體過小就不必壓縮(這裏設置最小範圍1K)
gzip_min_length  1024; 

#Nginx作爲反向代理的時候啓用,
#param:off|expired|no-cache|no-sotre|private|no_last_modified|no_etag|auth|any]
#expample:gzip_proxied no-cache;
#off – 關閉全部的代理結果數據壓縮
#expired – 啓用壓縮,若是header中包含」Expires」頭信息
#no-cache – 啓用壓縮,若是header中包含」Cache-Control:no-cache」頭信息
#no-store – 啓用壓縮,若是header中包含」Cache-Control:no-store」頭信息
#private – 啓用壓縮,若是header中包含」Cache-Control:private」頭信息
#no_last_modified – 啓用壓縮,若是header中包含」Last_Modified」頭信息
#no_etag – 啓用壓縮,若是header中包含「ETag」頭信息
#auth – 啓用壓縮,若是header中包含「Authorization」頭信息
#any – 無條件壓縮全部結果數據

gzip_proxied     any;

#Nginx做爲反向代理的時候啓用,開啓或者關閉後端服務器返回的結果,匹配的前提是後端服務器必需要返回包含"Via"的 header頭。
gzip_proxied expired no-cache no-store private auth;

#壓縮比例,比例越大,壓縮時間越長。
#默認是1 
#建議 nginx gzip級別爲4
gzip_comp_level  4;

#哪些文件能夠被壓縮
gzip_types       text/plain text/html text/javascript text/xml text/css application/x-javascript application/xml;

#無視IE6這個笨蛋
gzip_disable  "MSIE [1-6]\.";
複製代碼

負載均衡

upstream mysvr {
    #weigth參數表示權值,權值越高被分配到的概率越大
    server 192.168.8.1x:3128 weight=5;#本機上的Squid開啓3128端口
    server 192.168.8.2x:80  weight=1;
    server 192.168.8.3x:80  weight=6;
}

location ~* /mysvr/ {
    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://mysvr/$request_uri;    
}
複製代碼

內容控制

http頭控制

add_header 這個指令用來增長協議頭:
add_header Cache-Control no-cache;
add_header Cache-Control no-store;
add_header Cache-Control max-age=60;
add_header Content-Encoding gzip
add_header Content-Type 'text/html; charset=utf-8';

if ($request_uri ~* "^/$|^/search/.+/|^/company/.+/") {
    add_header    Cache-Control  max-age=3600;
}

if ($request_uri ~* "^/search-suggest/|^/categories/") {
    add_header    Cache-Control  max-age=86400;
}
複製代碼

直接簡單粗暴的返回狀態碼及內容文本:

location = /do_not_delete.html {
    return 200 "hello.";
}
複製代碼

SSL HTTPS

server {
	listen 443;
	
	# 這裏是ssl證書文件
	ssl on;
	ssl_certificate /app/certfull_chain.pem; # 換成本身的
	ssl_certificate_key /app/cert/private.key; # 換成本身的
	ssl_session_timeout 5m;
	ssl_protocols TLSv1 TLSv1.1 TLSv1.2; #按照這個協議配置
	ssl_ciphers ECDHE-RSA-AES128-GCM-SHA256:HIGH:!aNULL:!MD5:!RC4:!DHE;#按照這個套件配置
	ssl_prefer_server_ciphers on;	
}
server {
  	# 80端口是http正常訪問的接口
  	listen 80;
  	server_name xxxxx.com;
  	# 在這裏,我作了https全加密處理,在訪問http的時候自動跳轉到https
  	rewrite ^(.*) https://$host$1 permanent;
}
複製代碼

上面須要用到證書文件,若有須要的小夥伴,請看我這篇《3分鐘搞定從申請ssl證書到域名服務器配置》(該篇是以Apache爲服務環境),小夥伴只需將的面.pem和.key文件替換

相關學習文章

nginx反向代理配置
Nginx入門(三)Nginx 配置反向代理服務器

掃一掃關注

相關文章
相關標籤/搜索