使用Nginx實現動靜分離

Nginx 是一個高性能的http服務器,可以用來實現動態代理,負載均衡,最近需做一個web,mobile的分流處理, 接下來就使用Nginx來分流web和mobile的請求。


靜態內容代理#

使用Nginx實現靜態內容代理很簡單,只需無行代碼即可。打開Nginx配置文件在配置文件中添加如下代碼。

  • Linux 系統配置文件目錄 /etc/nginx/nginx.conf
  • OSX 系統配置文件目錄 /usr/local/etc/nginx/nginx.conf
<code>server {
listen 80 default_server; #指定監聽端口
server_name www.example.com; #制定服務器域名或者ip
location / {
root /usr/share/nginx/html; #服務器中存放靜態文件的目錄
index index.html index.htm; #默認訪問頁面
}
} /<code>

後臺服務#

通常前臺靜態文件和後臺rest service是分開開發的,開發時可以用mock測試,部署的時候通過nginx 路由前端的http請求到後臺服務器即可。

<code>server {
listen 81;
server_name 99.99.99.99 example.com;
root /usr/share/nginx/html;
index index.html index.htm;

#proxy_set_header 來設置
location /api {

proxy_pass http://api.example.com/; # 指定後臺服務器api地址
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; #是用來識別通過HTTP代理或負載均衡方式連接到Web服務器的客戶端最原始的IP地址的HTTP請求頭字段
proxy_set_header X-Forwarded-Proto $scheme; # $scheme 用來指明使用http還是https協議
proxy_set_header X-Forwarded-Port $server_port; #代理端口
}
}/<code>

通過以上代碼我們就實現了動靜隔離,靜態代碼部署網站的靜態文件(js,css,html,images), 後臺服務通過代理訪問

分離移動端和桌面端#

通常網站的入口都是統一的,由於web端和移動端有不同的屬性,所以為了更好的用戶體驗需要兩套代碼, 我們希望使用移動客戶端的希望他訪問A頁面,桌面端的訪問B頁面,此時就需要分離用戶設備。

<code>    server {
listen 80;
server_name 99.99.99.99 example.com;

# 通過`http_user_agent`來判斷用戶訪問的設備,當發現用戶使用的是移動設備就把請求重寫,訪問指定的移動端頁面

注意:if和( 之間必須有一個空格否則nginx啟動時會報錯
if ($http_user_agent ~* '(iPhone|iPod|iPad|Android|BlackBerry|webOS|Windows Phone'){
rewrite ^(.*) http://mobile.example.com/ permanent;
}

}

server {
listen 80;
server_name 10.10.10.10 mobile.example.com;

root /var/www/html/mobile;
index index.html index.htm;

location /api {
proxy_pass http://api.example.com/; # 指定後臺服務器api地址
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; #是用來識別通過HTTP代理或負載均衡方式連接到Web服務器的客戶端最原始的IP地址的HTTP請求頭字段
proxy_set_header X-Forwarded-Proto $scheme; # $scheme 用來指明使用http還是https協議
proxy_set_header X-Forwarded-Port $server_port; #代理端口
}
}

/<code>


分享到:


相關文章: