Installation
Ubuntu under
sudo apt-get install Nginx
Start
Start the startup file under Sudo/etc/init.d/nginx start #通过init. D.
sudo service Nginx start# is launched via the Ubuntu Services Manager
Configuration file Location
Compiling the installation
1. Prerequisites
(1). gcc
(2). Pcre (Perl compatible Regular Expression)
Apt-get Install Libpcre3 Libpcre3-dev
(3). zlib
Apt-get Install ZLIBLG Zliblg-dev
(4). OpenSSL
Apt-get install OpenSSL Opensll-dev
#如果非apt, can be handled by manually compiling the installation using the download package
2. Download package
Www.nginx.net Download stable version
wget http://nginx.org/download/nginx-1.4.4.tar.gz
3. Decompression Installation
TAR-XZVF nginx-1.4.4.tar.gz
#默认, install directory/usr/local/nginx
./configure make make
install
#配置
./configure--conf-path=/etc/nginx/nginx.conf
You can configure some other options
After installation, view the configuration summary in the following directory
4.init Script
Need to create an init script for Nginx
Get one from the internet and put it in/etc/init.d/nginx
Recommended Compilation Configuration
1. The use of different prefix to facilitate the designation of different versions, but also easy to upgrade
./configure--prefix=/usr/local/nginx-1.4.4
Basic operations
View Help
/usr/local/nginx/sbin/nginx-h
Stop process now (term signal)
/usr/local/nginx/sbin/nginx-s stop
Moderate stop process (quit signal)
/usr/local/nginx/sbin/nginx-s quit
Reload
/etc/init.d/nginx Reload #有init脚本情况下
/usr/local/nginx/sbin/nginx-s Reload #原生
Detect if the configuration file is correct
/usr/local/nginx/sbin/nginx-t #生产路径下的
/usr/local/nginx/sbin/nginx-t-c/home/ken/tmp/test.conf #可以测试某个临时文件
HTTP basic Configuration
Configuration Instructions
Note, #
Each instruction is always ended with a good score (;)
Configuration inheritance: Nested sections inherit the settings of their parent extents by nesting other extents in one block
String, you can have no quotes, but if there are special characters (spaces, semicolons, curly braces) that need to be enclosed in quotation marks
Unit: Size (k/k m/m) time value (ms/s/m/h/d/w/m/y default s)
The module provides variable values that can be read and assigned (each module provides a list of variables that needs to be checked by itself)
Configuration file directory structure
/usr/local/nginx/conf/
-Mime.types A list of file extensions that are associated with MIME types
-fastcgi.conf configuration files related to FastCGI
-proxy.conf configuration files related to proxy
-Nginx.conf The application's basic configuration file
-sites/
|-a.conf #允许给每个单独网站建立一个配置文件
|-b.conf
|-dir/
|-c.conf
Need to use include command in nginx.conf
Include sites/*.conf;
Include sites/*/*.conf;
Configuration file Structure
HTTP {#嵌入配置文件的根部, one HTTP can be configured with multiple server
server {#声明一个站点
server_name www.website.com; #监听的主机名
listen 80; # The IP address and port number used by the listening socket
error_page 404/not_found.html;
Error_page 501 502 503 504/server_error.html;
Index index.html;
root/var/www/website/com/html; #定义文档的根目录
#location, matching the URI of the client request through the established pattern
location/{#网站的特定位置
}
location/admin/{#网站的特定位置 #
alias/var/www/locked/#只能放在 Location section, providing an alias for the specified path
}
#操作符, matching is not
location =/ABCD {#精确匹配 with defined order, cannot use regular
}
location/abc/{#url必须以指定模式开始, cannot use regular
}
Location ^~/abcd$ {#吴标致行为, URI positioning must start in the specified mode, if matched, stop searching for other modes
}
location ~ ^/abcd$ {#正则匹配, case-sensitive
}
Location ~* ^/abcd$ {#正则匹配, case-insensitive
}
location @test {#定义location区段名, clients cannot access, internal requests can be generated, such as Try_files or Error_ Page
}}}
Module
of modular
Nginx's real charm lies in its module, where the entire application is built on a modular system that can be enabled or disabled at compile time for each module
Index module
define which index page to go back to
Index index.php index.html/data/website/index.html;
#可以指定多个, but Ngxin provides the first file found
Log Module
Access_log/file/path;
Error_log/file/path error; #level: Debug/info/notice/warn/error/crit
Log Format
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/var/log/test.log main;
Real IP Module
The default compilation Nginx does not contain this module
When the user request is forwarded through Nginx, the application of the receiving request is to get the real IP of the user (the IP of the server is forwarded)
Real_ip_header x-forwarded-for;
Access Module
You can disable IP segments
Grammar
#如果规则之间有冲突, the first matching rule is the quasi-
deny IP;
Deny subnet;
Allow IP;
Allow subnet;
# block all IPs
deny all ;
# allow all IPs
allow all ;
Configure a blockips.conf, and then include in the nginx.conf
e.g
Location {
allow 127.0.0.1; #允许本地ip note order, allow to put in front of
deny all; #禁止其他ip
}
Rewrite module
function: Perform URL redirection, allowing you to remove malicious URLs, including multiple parameters (modify)
Using regular matching, grouping and referencing to achieve the goal
Break/return/set, etc.
if (-f $uri) {break
}
if ($uri ~ ^/admin/) {return
403;
}
if ($uri ~ ^/search/(. *) $) {
set $query $;
Rewrite ^/search.php?q= $query?;
}
Example
A:http://website.com/search/some-search-keywords
B:http://website.com/search.php?q=some-search-keywords
rewrite ^/search/(. *) $/search.php?q=$1?;
A:http://website.com/user/31/james
b:http://website.com/user.php?id=31&name=james
rewrite ^/user/([ 0-9]+)/(. +) $/user.php?id=$1&name=$2?;
A:HTTP://WEBSITE.COM/INDEX.PHP/PARAM1/PARAM2/PARAM3
b:http://website.com/index.php/?p1=param1&p2= Param2&p3=param3
Rewrite ^/index.php/(. *)/(. *)/(. *) $/index.php?p1=$1&p2=$2&p3=$3?;
Rewrite syntax
Options
Last: Indicates completion of rewrite
Break: After this rule match completes, terminates the match, no longer matches the following rule
Redirect: Return 302 temporary redirect, the address bar will show the address after the jump
Permanent: Returns 301 Permanent redirect, the address bar will show the address after the jump
Proxy Module
default module, allows you to speak to the client's HTTP request to the back-end server
Location/{
Proxy_pass_header Server; #该指令强制一些被忽略的头传递到客户端
proxy_redirect off; #允许改写出现在HTTP头却被后端服务器触发重定向的URL , the corresponding itself does not do any processing
proxy_set_header host $http _host; #允许你重新定义代理header值再转到后端服务器. The target server can see the client's original host name
proxy_set_ Header X-real-ip $remote _addr; #目标服务器可以看到客户端的真实ip, rather than the IP proxy_set_header x-scheme $scheme of the forwarding server
;
Proxy_pass http://localhost:8080;
}
Upstream module
Upstream Up_name {
server 192.168.0.1:9000 weight=5; #权重
server 192.168.0.2:9000 weight=5 the max_fails=5 fail_ timeout=60s; #在60s内, its error communication is more than 5 times, that the service fails
server 192.168.0.3:9000 down; #服务标记为离线, no longer uses
server 192.168.0.4:9000 backup; #备份服务器, All other downtime is enabled
}
Other
To configure a static table of contents
location/static/
{
root/var/www/app/;
AutoIndex off;
Load Balancing
HTTP {
include mime.types;
Default_type Application/octet-stream;
Keepalive_timeout;
Tcp_nodelay on;
Upstream Up_localhost {
server 127.0.0.1:8000 weight=5;
Server 127.0.0.1:8001 weight=10;
}
server {
listen;
server_name localhost;
Location/{
proxy_pass http://up_localhost;
Proxy_set_header Host $host;
Proxy_set_header x-real_ip $remote _addr;
Proxy_set_header x-forwarded-for $proxy _add_x_forwarded_for
}}
}
Controlling page Caching
Location ~ \. (Htm|html|gif|jpg|jpeg|png|bmp|ico|css|js|txt) $ {
Root/opt/webapp;
Expires 24h;
}
Expires 1 January, 1970, 00:00:01 GMT;
expires 60s;
Expires 30m;
Expires 24h;
Expires 1d;
Expires Max;
Expires off;
Built-in variables for Nginx
$arg _parameter This variable contains the value of the GET request PARAMETER when the query string is being queried.
$args this variable equals the parameters in the request line.
The client address in the form of a $binary _remote_addr binary code.
$body _bytes_sent
$content the Content-length field in the _length request header.
$content the Content-type field in the _type request header.
$cookie the value of the _cookie cookie cookie.
$document _root The value specified in the root directive for the current request.
$document _uri is the same as $uri.
$host the Host header field in the request, and if the primary header in the request is not available, the server name of the requested server is processed.
$is _args If the $args setting, the value is "?", otherwise "".
$limit _rate This variable can limit the connection rate.
$nginx _version the currently running Nginx version number.
$query _string is the same as $args.
$remote the IP address of the _ADDR client.
$remote the port of the _port client.
$remote _user user name that has been validated by Auth Basic module.
$request _filename The file path of the current connection request, which is generated by the root or alias directive and the URI request.
$request _body this variable (0.7.58+) contains the primary information for the request. This is useful in location that use Proxy_pass or fastcgi_pass directives.
$request the temporary file name of the _body_file client request principal information.
$request _completion Request Complete
$request _method This variable is a client-requested action, usually a get or post. including 0.8.20 and previous versions, this variable is always the action in main request, and if the current request is a child request, the current requested action is not used.
$request _uri This variable is equal to the original URI that contains some client request parameters, it cannot be modified, see $uri change or rewrite the URI.
$schemeHTTP methods (such as Http,https). On-Demand Use, example:
Rewrite ^ (. +) $ $scheme://example.com$1 redirect;
$server _addr server address, you can determine this value after a system call is completed, and if you want to bypass system calls, you must specify the address in listen and use the bind parameter.
$server _name server name.
$server _port request arrives at the server's port number.
$server the protocol that the _protocol requests to use, usually http/1.0 or http/1.1.
$uri the current URI in the request (without the request parameter, with the parameter at $args), can be different from the $request_uri value passed by the browser, either through internal redirection or by using the index directive.
Use a standalone directory, and then include specific configuration
Directory
nginx.conf
site/
a.conf
b.conf
nginx.conf
http {
...
.. include/etc/nginx/conf.d/*.conf;
Include sites/*.conf;
}
Gzip on
add to HTTP module, turn on gzip, note that Gzip_types is configured to be a compressed resource type
Nginx.conf
HTTP {.... gzip on;
Gzip_min_length 1k;
Gzip_comp_level 5;
Gzip_proxied expired No-cache No-store private auth; Gzip_types text/plain text/css application/javascript text/javascript application/x-javascript text/xml application/
XML Application/xml+rss Application/json image/x-icon image/png image/jpg image/jpeg;
Gzip_vary on;
For multi processers nginx.conf worker_processes 4;
Events {Worker_connections 2048;
Use Epoll;
Multi_accept on;
} worker_rlimit_nofile 100000; Static file cache location ~* \.
(?: Css|js) $ {expires 12h;
Access_log off;
Add_header Cache-control "public";
Proxy_pass http://127.0.0.1:5000;
Proxy_redirect off;
Proxy Pass location/{Proxy_pass http://127.0.0.1:8000;
Proxy_pass_header Server;
Proxy_set_header x-forwarded-for $proxy _add_x_forwarded_for;
Proxy_set_header X-real-ip $remote _addr;
Proxy_set_header X-scheme $scheme;
Proxy_set_header Host $http _host; prOxy_redirect off;
}
You can set the timeout time
Proxy_connect_timeout 500s;
Proxy_read_timeout 500s;
Proxy_send_timeout 500s;
Static directory or file
location/movies/{
alias/volumes/media/movies/;
Allow all;
}
Location =/abc.txt {
alias/data/www/static/abc.txt;
Expires 30d;
Access_log off;
Static station
server {
listen 192.168.1.1:80;
server_name www.abc.com;
Client_max_body_size 1M;
Access_log Logs/blog_access.log;
Error_log Logs/blog_error.log;
Root/data/static_site_dir;
Index index.html;
}
Return
Direct return
Grammar
return http_code;
return http_code "content";
e.g.
location/api/test/{return
403;
}
location/stat/{return
204;
}
location/ping/{return
}
For mobile
move end and site side jump to each other
Location =/{Try_files $uri @mobile_rewrite;
} location ~ ^/(login|register|search|album|404|album/\d+|item/\d+|topic) $ {try_files $uri @mobile_rewrite; } location @mobile_rewrite {if ($http _user_agent ~* (android|bb\d+|meego). +mobile|avantgo|bada\/|blackberry|bla Zer|compal|elaine|fennec|hiptop|iemobile|ip (hone|od) |iris|kindle|lge |maemo|midp|mmp|netfront|opera m (ob|in) i| Palm (OS)? | Phone|p (Ixi|re) \/|plucker|pocket|psp|series (4|6) 0|symbian|treo|up\.
(Browser|link) |vodafone|wap|windows (ce|phone) |xda|xiino ") {set $mobile _rewrite perform; } if ($http _user_agent ~* "^ (1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac (er|oo|s\-) |ai (KO|RN) |al (av|ca |co) |amoi|an (EX|NY|YW) |aptu|ar (Ch|go) |as (te|us) |attw|au (di|\-m|r |s) |avan|be (CK|LL|NQ) |bi (lb|rd) |bl (Ac|az) |BR (E |V) w|bumb|bw\-(n|u) |c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co (mp|nd) |craw|da (it|ll|ng) |dbte|dc\-s|devi| Dica|dmob|do (c|p) o|ds (12|\-d) |el (49|ai) |em (L2|ul) |er (ic|k0) |esl8|ez ([4-7]0|os|Wa|ze) |fetc|fly (\-|_) |g1 U|g560|gene|gf\-5|g\-mo|go (\.w|od) |gr (Ad|un) |haie|hcit|hd\-(m|p|t) |hei\-|hi (Pt|ta) |hp ( I|IP) |hs\-c|ht (c (\-| |_|a|g|p|s|t) |tp) |hu (AW|TC) |i\-(20|go|ma) |i230|iac (|\-|\/) |ibro|idea|ig01|ikom|im1k|inno| Ipaq|iris|ja (t|v) a|jbro|jemu|jigs|kddi|keji|kgt (|\/) |klon|kpt |kwc\-|kyo (c|k) |le (no|xi) |lg (g|\/(k|l|u) |50|54|\- [A-w]) | Libw|lynx|m1\-w|m3ga|m50\/|ma (Te|ui|xo) |MC (01|21|CA) |m\-cr|me (Rc|ri) |mi (o8|oa|ts) |mmef|mo (01|02|bi|de|do|t (\-| | O|V) |zz) |mt (50|p1|v) |mwbp|mywa|n10[0-2]|n20[2-3]|n30 (0|2) |n50 (0|2|5) |n7 (0 (0|1) |10) |ne ((c|m) \-|ON|TF|WF|WG|WT) | NOK (6|i) |nzph|o2im|op (TI|WV) |oran|owg1|p800|pan (a|d|t) |PDXG|PG (13|\-([1-8]|c)) |PHIL|PIRE|PL (AY|UC) |pn\-2|po (CK |rt|se) |PROX|PSIO|PT\-G|QA\-A|QC (07|12|21|32|60|\-[2-7]|i\-) |qtek|r380|r600|raks|rim9|ro (Ve|zo) |s55\/|sa (ge|ma |mm|ms|ny|va) |SC (01|h\-|oo|p\-) |sdk\/|se (c (\-|0|1) |47|mc|nd|ri) |sgh\-|shar|sie (\-|m) |SK\-0|SL (45|id) |sm (al|ar| B3|IT|T5) |so (ft|ny) |sp (01|h\-|v\-|v) |sy (01|MB) |t2 (18|50) |t6 (00|10|18) |ta (gt|lk) |tcl\-|tdg\-|tel (i|m) |tiM\-|t\-mo|to (Pl|sh) |ts (70|M\-|M3|M5) |tx\-9|up (\.b|g1|si) |utst|v400|v750|veri|vi (rg|te) |vk (40|5[0-3]|\-v) |vm40| VODA|VULC|VX (52|53|60|61|70|80|81|83|85|98) |w3c (\-|) |
Webc|whit|wi (g |nc|nw) |wmlb|wonu|x700|yas\-|your|zeto|zte\-) "{set $mobile _rewrite perform;
} if ($arg _mobile = ' no ') {set $mobile _rewrite do_not_perform;
} if ($arg _mobile = ' yes ') {set $mobile _rewrite perform;
} if ($mobile _rewrite = perform) {rewrite ^ http://$server _name/m$request_uri permanent;
Break
} Proxy_pass http://127.0.0.1:5000;
Proxy_set_header x-forwarded-for $proxy _add_x_forwarded_for;
Proxy_set_header X-real-ip $remote _addr;
Proxy_set_header Host $http _host;
Proxy_redirect off;
} location/m/{set $pc _rewrite 1; if ($http _user_agent ~* "(android|bb\d+|meego). +mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec| Hiptop|iemobile|ip (hone|od) |iris|kindle|lge |maemo|midp|mmp|netfront|opera m (ob|in) i|pALM (OS)? | Phone|p (Ixi|re) \/|plucker|pocket|psp|series (4|6) 0|symbian|treo|up\.
(Browser|link) |vodafone|wap|windows (ce|phone) |xda|xiino ") {set $pc _rewrite 0; } if ($http _user_agent ~* "^ (1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac (er|oo|s\-) |ai (KO|RN) |al (av|ca |co) |amoi|an (EX|NY|YW) |aptu|ar (Ch|go) |as (te|us) |attw|au (di|\-m|r |s) |avan|be (CK|LL|NQ) |bi (lb|rd) |bl (Ac|az) |BR (E |V) w|bumb|bw\-(n|u) |c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co (mp|nd) |craw|da (it|ll|ng) |dbte|dc\-s|devi| Dica|dmob|do (c|p) o|ds (12|\-d) |el (49|ai) |em (L2|ul) |er (ic|k0) |esl8|ez ([4-7]0|os|wa|ze) |fetc|fly (\-|_) |g1 u|g560| Gene|gf\-5|g\-mo|go (\.w|od) |gr (Ad|un) |haie|hcit|hd\-(m|p|t) |hei\-|hi (Pt|ta) |hp (I|IP) |hs\-c|ht (c (\-| |_|a|g|p|s| T) |tp) |hu (AW|TC) |i\-(20|go|ma) |i230|iac (|\-|\/) |ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja (t|v) a|jbro|jemu| JIGS|KDDI|KEJI|KGT (|\/) |klon|kpt |kwc\-|kyo (c|k) |le (no|xi) |lg (g|\/(k|l|u) |50|54|\-[a-w]) |libw|lynx|m1\-w|m3ga| M50\/|ma (Te|ui|xo) |MC (01|21|CA) |m\-cr|me (Rc|ri) |mi (O8|oa|ts) |mmef|mo (01|02|bi|de|do|t (\-| |o|v) |zz) |mt (50|p1|v) |mwbp|mywa|n10[0-2]|n20[2-3]|n30 (0|2) |n50 (0|2|5) |n7 (0 (0|1) |10) |ne ((c|m) \-|on|tf|wf|wg|wt) |nok (6|i) |nzph|o2im|op (TI|WV) |oran|owg1|p800|pan (a|d|t) |PDXG|PG (13|\-([1-8 ]|C)) |PHIL|PIRE|PL (AY|UC) |pn\-2|po (ck|rt|se) |PROX|PSIO|PT\-G|QA\-A|QC (07|12|21|32|60|\-[2-7]|i\-) |qtek|r380| R600|raks|rim9|ro (Ve|zo) |s55\/|sa (Ge|ma|mm|ms|ny|va) |sc (01|h\-|oo|p\-) |sdk\/|se (c (\-|0|1) |47|mc|nd|ri) |sgh\-| Shar|sie (\-|m) |SK\-0|SL (45|id) |sm (AL|AR|B3|IT|T5) |so (ft|ny) |sp (01|h\-|v\-|v) |sy (01|MB) |t2 (18|50) |t6 (00|10|18) | Ta (gt|lk) |tcl\-|tdg\-|tel (i|m) |tim\-|t\-mo|to (pl|sh) |ts (70|M\-|M3|M5) |tx\-9|up (\.b|g1|si) |utst|v400|v750|veri| VI (RG|TE) |VK (40|5[0-3]|\-v) |vm40|voda|vulc|vx (52|53|60|61|70|80|81|83|85|98) |w3c (\-|) |
Webc|whit|wi (g |nc|nw) |wmlb|wonu|x700|yas\-|your|zeto|zte\-) "{set $pc _rewrite 0;
} if ($pc _rewrite = 1) {rewrite ^/m/(. *) $ http://$server _name/$1 permanent;
} Proxy_pass http://127.0.0.1:5000; Proxy_set_header X-FORWArded-for $proxy _add_x_forwarded_for;
Proxy_set_header X-real-ip $remote _addr;
Proxy_set_header Host $http _host;
Proxy_redirect off;
} Redirect to www server {server_name abc.com;
Rewrite ^ (. *) http://www.abc.com$1 permanent;
} Allow and Deny
Access IP Control
location/test/{
allow 192.168.1.1;
Deny all;
}
Load Balancing
nginx.conf
HTTP {
upstream A {
server 192.168.1.1:5000;
Server 192.168.1.2:5000;
}
}
Sites/a.conf
server {
location/{
proxy_pass A;
}
}
Other
Check configuration file Correctness
Reload Configuration