Nginx - 配置
Nginx
標(biāo)簽 : nginx
Nginx
nginx [engine x] is an HTTP and reverse proxy server, a mail proxy server, and a generic TCP/UDP proxy server, originally written by Igor Sysoev. For a long time, it has been running on many heavily loaded Russian sites including Yandex, Mail.Ru, VK, and Rambler. According to Netcraft, nginx served or proxied 25.64% busiest sites in April 2016. Here are some of the success stories: Netflix, Wordpress.com, FastMail.FM.The sources and documentation are distributed under the 2-clause BSD-like license.Commercial support is available from Nginx, Inc.Nginx是一款輕量級的Web服務(wù)器/反向代理服務(wù)器及電子郵件(IMAP/POP3)代理服務(wù)器,由俄羅斯工程師Igor Sysoev開發(fā),供俄國大型入口網(wǎng)站及搜索引擎Rambler使用.其源代碼以BSD-like協(xié)議發(fā)布. 其特點是內(nèi)存占用少,并發(fā)能力強(qiáng), 因此被國內(nèi)很多大型網(wǎng)站(如京東/淘寶)采用.
(主頁/介紹/文檔).
編譯安裝
- wget http://nginx.org/download/nginx-1.10.0.tar.gz
- tar -zxvf nginx-1.10.0.tar.gz
./configure --prefix=/usr/local/nginx
configure階段可能會遇到缺少依賴庫的提示(如pcre/zlib),此時需要安裝這些依賴才能繼續(xù):
- yum install pcre pcre-devel
- yum install zlib zlib-devel
make && make install
安裝完成后可在/usr/local/nginx/目錄下生成如下文件夾:
| conf | nginx配置文件 |
| html | 網(wǎng)頁文件 |
| logs | nginx日志文件 |
| sbin | nginx可執(zhí)行文件 |
- /usr/local/nginx/sbin/nginx
啟動, Nginx默認(rèn)占用80端口,可在nginx.conf中更改.
Nginx信號
關(guān)于Linux信號相關(guān)知識, 可參考系列博客Linux信號實踐, 在此, 我們僅介紹Nginx捕獲的幾個信號.
nginx can be controlled with signals.
- Kill -信號名 PID
| TERM/INT | fast shutdown |
| QUIT | graceful shutdown |
| HUP | changing configuration, keeping up with a changed time zone , starting new worker processes with a new configuration, graceful shutdown of old worker processes |
| USR1 | re-opening log files |
| USR2 | upgrading an executable file |
| WINCH | graceful shutdown of worker processes |
以上信號作用亦可通過編譯出的nginx二進(jìn)制文件實現(xiàn):
To start nginx, run the executable file. Once nginx is started, it can be controlled by invoking the executable with the -s parameter. Use the following syntax:
nginx -s signal
配置
- nginx.config
Server
在Nginx內(nèi)可配置虛擬主機(jī), 只需在nginx.conf中添加一個server元素:
server {listen 801;server_name www.feiqing.me;location / {root /www.feiqing.me/;index index.html index.htm;} }Log
- 自定義log_format
- servlet內(nèi)引用
- 示例
為www.feiqing.me server單獨配置一個log:
Location
Syntax: location [ = | ~ | ~* | ^~ ] uri { ... } location @name { ... } Default: — Context: server, locationSets configuration depending on a request URI.
Nginx允許自定義location塊,通過指定的模式與客戶端請求的URI相匹配,Nginx可將網(wǎng)站根據(jù)URI進(jìn)行劃分,將網(wǎng)站的不同部分定位到不同的處理方式上:
- location修飾符
location第一個可選參數(shù)是一個符號,用來定義Nginx的匹配模式:
| @ | 指定一個命名的location,一般只用于內(nèi)部重定向請求 |
| = | 精確匹配模式: URI的定位必須與指定的模式精確匹配 |
| (無) | 一般匹配模式: URI的定位必須以指定模式開始, 不可以使用正則表達(dá)式 |
| ~ | 區(qū)分大小寫的正則匹配模式: 客戶端請求URI與指定正則表達(dá)式匹配必須區(qū)分大小寫 |
| ~* | 不區(qū)分大小寫的正則匹配模式 |
| ^~ | 類似于(無)模式的行為, URI的定位必須以指定模式開始, 不同的是, 如果模式匹配, 那么Nginx就停止搜索其他模式 |
| !~/!~* | 分別為區(qū)分大小寫不匹配和不區(qū)分大小寫不匹配的正則 |
| / | 通用匹配, 任何請求都會匹配到 |
有多個location配置情況下的匹配順序:
- 帶有=修飾符的location: 如果指定pattern與URI 精確匹配, 則Nginx使用該location設(shè)置.
- 沒有修飾符的location: 如果指定pattern與URI 精確匹配,則使用之.
- 帶有^~修飾符的location: 如果指定pattern與URI 開始匹配, 則使用之.
- 帶有~/~*修飾符的location: 如果指定pattern與URI 匹配, 則使用之.
- 沒有修飾符的location: 如果指定pattern與URI 開始匹配, 則使用之.
- 通用匹配/.
示例:
關(guān)于location詳細(xì)內(nèi)容可參考Nginx-ngx_http_core_module模塊文檔.
Rewrite
Rewrite用于實現(xiàn)URI重寫, URI重寫可以讓我們在改變網(wǎng)站結(jié)構(gòu)時,無需修改原先暴露出去的URL, 并且在一定程度上提高網(wǎng)站安全性;
The ngx_http_rewrite_module module is used to change request URI using regular expressions, return redirects, and conditionally select configurations.
Nginx的Rewrite的實現(xiàn)依賴于PCRE(Perl Compatible Regular Expressions:Perl兼容正則表達(dá)式)庫, 因此在編譯Nginx前, 需要確保系統(tǒng)中已經(jīng)包含該依賴.
注意: 正則表達(dá)式的元字符{與}會與nginx.conf中block定界符{ ... }有沖突, 如果需要在nginx.conf內(nèi)寫一個包含花括號的正則表達(dá)式,需要將表達(dá)式放在單引號/雙引號之間.
- Rewrite指令執(zhí)行順序:
- 執(zhí)行server塊rewrite指令;
- 執(zhí)行l(wèi)ocation匹配;
- 執(zhí)行選定location中的rewrite指令;
如果其中某步URI被重寫,則重新循環(huán)執(zhí)行1-3步,直到找到真實存在的文件. 但循環(huán)次數(shù)不能超過10次, 否則Nginx返回500-Internal Server Error.
指令
if 指令
Syntax: if (condition) { ... } Default: — Context: server, location- The specified condition is evaluated. If true, this module directives specified inside the braces are executed, and the request is assigned the configuration inside the if directive. Configurations inside the if directives are inherited from the previous configuration level.
if條件可以是如下內(nèi)容:
| 一個變量名 | 只有該變量是空字符串或者以0開始的字符串, 才為false |
| 使用=/!= | 比較一個變量和字符串 |
| 使用~/~* | 變量與正則表達(dá)式進(jìn)行匹配的變量 |
| 使用-f/!-f | 檢查一個文件是否存在 |
| 使用-d/!-d | 檢查一個目錄是否存在 |
| 使用-e/!-e | 檢查一個文件、目錄、符號鏈接是否存在 |
| 使用-x/!-x | 檢查一個文件是否可執(zhí)行 |
- 示例
- 其他
break 指令
Syntax: break; Default: — Context: server, location, if- Stops processing the current set of ngx_http_rewrite_module directives(停止執(zhí)行當(dāng)前虛擬主機(jī)的后續(xù)rewrite指令).
return 指令
Syntax: return code [text];return code URL;return URL; Default: — Context: server, location, if- Stops processing and returns the specified code to a client. The non-standard code 444 closes a connection without sending a response header(停止處理并返回指定狀態(tài)碼給客戶端,非標(biāo)準(zhǔn)狀態(tài)碼444表示關(guān)閉連接且不給客戶端發(fā)送響應(yīng)頭).
該指令用于直接向客戶端返回響應(yīng)狀態(tài)碼,從0.8.42版本起,return支持響應(yīng)URL重定向(對于301/302/303/307),或者文本響應(yīng)(對于其他狀態(tài)碼).
注意: 對于302/307, 返回的URL中應(yīng)包含"http://"/"https://".對于文本或者URL重定向可以包含變量.
if ($http_user_agent ~ Chrome) {return 302 http://www.baidu.com; }set 指令
Syntax: set $variable value; Default: — Context: server, location, if- Sets a value for the specified variable. The value can contain text, variables, and their combination.
rewrite 指令
Syntax: rewrite regex replacement [flag]; Default: — Context: server, location, if- If the specified regular expression matches a request URI, URI is changed as specified in the replacement string(如果一個URI匹配指定的正則表達(dá)式, URI就按照replacement形式重寫). The rewrite directives are executed sequentially in order of their appearance in the configuration file. It is possible to terminate further processing of the directives using flags(rewrite按配置文件中出現(xiàn)的順序執(zhí)行, 但flags標(biāo)志可以停止繼續(xù)處理). If a replacement string starts with “http://” or “https://”, the processing stops and the redirect is returned to a client.
注意: 接收到的URI不包含host地址(如example.com), 也不包含URL中的請求參數(shù)(如?arg1=value1&arg2=value).
實例-偽靜態(tài)化
使用Rewrite功能將JavaWeb中的動態(tài)URL(xx.do?arg1=xx&arg2=xx)以靜態(tài)URL替換(xx-xx-xx.html).
server {listen 800;server_name localhost;#charset koi8-r;#access_log logs/host.access.log main;location / {root html;index index.html index.htm;}location ~* (/javis/teacher/).*(.html)$ {rewrite /javis/teacher/(\w+)-(\w+)-(\w+)\.html /javis/teacher/$1.do?name=$2&password=$3;}location ~* \.(do|jsp|jspx)?$ {proxy_set_header X-Forwarded-For $remote_addr;proxy_pass http://10.45.156.170:80;}}location ~* (/javis/teacher/).*(.html)$ { ... }會攔截所有/javis/teacher/ 目錄下以.html結(jié)尾的靜態(tài)URL,將其重寫為.do結(jié)尾的動態(tài)URL(/javis/teacher/login-new_name-password.html -> /javis/teacher/login.do?name=new_name&password=password ), 然后location ~* \.(do|jsp|jspx)?$ { ... }提供反向代理功能,將所有以.do結(jié)尾的URL轉(zhuǎn)發(fā)到http://10.45.156.170:80地址, 由Java的后端Server提供真正的服務(wù)(反向代理相關(guān)知識可參考我的下一篇Nginx博客).
Gzip
Gzip(GNU-ZIP)是一種壓縮技術(shù),經(jīng)壓縮后的頁面可能只有原大小的30%,大大減小了網(wǎng)絡(luò)傳輸開銷,瀏覽器加載網(wǎng)頁的速度也會提升不少,但這項技術(shù)需要瀏覽器的配合(在服務(wù)端對網(wǎng)頁進(jìn)行壓縮, 在瀏覽器對其解壓并解析),由于現(xiàn)代瀏覽都支持很多種解壓縮的方式(如Chrome: Accept-Encoding:gzip, deflate, sdch), 因此瀏覽器方面不需要我們擔(dān)心.
Nginx的gzip模塊是內(nèi)置的, 由ngx_http_gzip_module 模塊實現(xiàn), 可在nginx.conf中配置使用:
The ngx_http_gzip_module module is a filter that compresses responses using the “gzip” method. This often helps to reduce the size of transmitted data by half or even more.
指令
Context: http, server, location, Gzip一共有9個指令可以設(shè)置:
| gzip on | off; | Enables or disables gzipping of responses. |
| gzip_buffers number size; | Sets the number and size of buffers used to compress a response. By default, the buffer size is equal to one memory page. This is either 4K or 8K, depending on a platform. |
| gzip_comp_level level; | Sets a gzip compression level of a response. Acceptable values are in the range from 1 to 9(推薦壓縮級別為6). |
| gzip_disable regex ...; | Disables gzipping of responses for requests with “User-Agent” header fields matching any of the specified regular expressions. |
| gzip_min_length length; | Sets the minimum length of a response that will be gzipped. The length is determined only from the “Content-Length” response header field. |
| gzip_http_version 1.0 | 1.1; | Sets the minimum HTTP version of a request required to compress a response(default 1.1). |
| gzip_types mime-type ...; | Enables gzipping of responses for the specified MIME types in addition to “text/html”. The special value “*” matches any MIME type (0.8.29). Responses with the “text/html” type are always compressed. |
| gzip_vary on | off; | Enables or disables inserting the “Vary: Accept-Encoding” response header field if the directives gzip, gzip_static, or gunzip are active. |
| gzip_proxied [flag]; | Enables or disables gzipping of responses for proxied requests depending on the request and response. The fact that the request is proxied is determined by the presence of the “Via” request header field. The directive accepts multiple parameters -> details |
實例-常用Gzip配置
http {## ...gzip on;gzip_min_length 1024;gzip_buffers 4 16k;gzip_comp_level 6;gzip_types text/plain application/x-javascript application/javascript application/xml text/css ;gzip_vary on;## ... }為了使Nginx能夠在全局范圍內(nèi)使用gzip,故將其放在http全局模塊中.如果需要對各個虛擬主機(jī)區(qū)別對待,可在對應(yīng)的server塊中添加自己的gzip指令.
通過以上Nginx服務(wù)器訪問一個網(wǎng)頁(前提: Content-Length > 1024), 會看到靜態(tài)資源文件的Response中新增了如下三個響應(yīng)頭:
Content-Encoding:gzip Transfer-Encoding:chunked Vary:Accept-Encoding注意:
1. 由于圖片/視頻/音頻之類文件壓縮比率很小, 且壓縮過程非常耗費CPU資源, 因此這類資源推薦不對其壓縮.
2. 較小的文件壓縮后很有可能會比原文件還大, 因此這類資源也推薦不對其壓縮.
Expires
對于網(wǎng)站圖片,尤其是新聞網(wǎng)站,圖片一旦發(fā)布,改動的可能非常小.因此我們希望用戶在第一訪問之后,圖片直接緩存在瀏覽器,而不再向服務(wù)端發(fā)送請求(不同于HTTP-304-Not Modified), 且能夠自定義緩存配置.這就用到了Nginx的expires功能.
Syntax: expires [modified] time; expires epoch | max | off; Default: expires off; Context: http, server, location, if in location- Enables or disables adding or modifying the “Expires” and “Cache-Control” response header fields provided that the response code equals 200, 201, 204, 206, 301, 302, 303, 304, or 307. A parameter can be a positive or negative time.
注意: 要確保服務(wù)器時間準(zhǔn)確,如果服務(wù)器時間落后于實際時間,可導(dǎo)致緩存失效.
實例-圖片緩存
- 配置圖片緩存時間為一天:
通過以上Nginx服務(wù)器訪問一個圖片(如nginx.png),會看到圖片的Response中添加了如下兩個響應(yīng)頭:
Cache-Control:max-age=86400 Expires:Fri, 20 May 2016 12:26:11 GMT再次刷新該URL, 在瀏覽器(如Chrome)中會看到這張圖片來自本地緩存:
總結(jié)
以上是生活随笔為你收集整理的Nginx - 配置的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Keras自定义Loss函数
- 下一篇: 玩转VIM编辑器-vim附加特性