Home>

installationUnder Ubuntu

sudo apt-get install nginx

start up

sudo /etc/init.d/nginx start #Start from the startup file under init.d.
sudo service nginx start #Start via ubuntu's service manager

Configuration file location

/etc/nginx/nginx.conf

Compile and install1. Prerequisites

(1) .gcc

apt-get install 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
#If it is not apt, you can use the download package to manually compile and install it.

2. Download the package

www.nginx.net download stable version

wget http://nginx.org/download/nginx-1.4.4.tar.gz

3. Unzip the installation

tar -xzvf nginx-1.4.4.tar.gz
#Default, installation directory/usr/local/nginx
./configure
make
make install
#Configuration
./configure --conf-path =/etc/nginx/nginx.conf

Can configure some other options

Check the configuration summary under the directory after installation

4.init script

Need to create an init script for nginx

Fish one from the internet,Put in /etc/init.d/nginx

Recommended compilation configuration

1. Use different prefixes to easily specify different versions,Also easy to upgrade

./configure --prefix =/usr/local/nginx-1.4.4

Basic operation

View help

/usr/local/nginx/sbin/nginx -h

Stop the process immediately (term signal)

/usr/local/nginx/sbin/nginx -s stop

Gently stop the process (quit signal)

/usr/local/nginx/sbin/nginx -s quit

Reload

/etc/init.d/nginx reload #With init script
/usr/local/nginx/sbin/nginx -s reload #Native

Check if the configuration file is correct

/usr/local/nginx/sbin/nginx -t #The production path
/usr/local/nginx/sbin/nginx -t -c /home/ken/tmp/test.conf #Can test a temporary file

http basic configuration

Configuration instructionsComment, #

Every instruction always ends with a good divide (;)

Configuration inheritance:nesting other sections in a block,The nested section will inherit the settings of its parent section

String, without quotes,But if there are special characters (spaces, semicolons, curly braces) need to be quoted

Unit:size (k/k m/m) time value (ms/s/m/h/d/w/m/y default s)

The module provides various variable values,Can be read and assigned (variable list provided by each module needs to be checked by itself)

Configuration file directory structure

/usr/local/nginx/conf /

-mime.types a list of file extensions,They are associated with mime types

-fastcgi.conf Fastcgi related configuration files

-proxy.conf proxy related configuration file

-Basic configuration file for nginx.conf application

-sites /

|-a.conf #Allow setting up a configuration file for each individual website

|-b.conf

|-dir /

|-c.conf

Need to use include command in nginx.conf

include sites/*. conf;
include sites/*/*. conf;

Configuration file structure

http {#Embed the root of the configuration file, Multiple servers can be configured in one http
  server {#declare a site
    server_name www.website.com;#Host name to listen on
    listen 80;#IP address and port number used by the listening socket
    error_page 404 /not_found.html;
    error_page 500 501 502 503 504 /server_error.html;
    index index.html;
    root/var/www/website/com/html;#Define the root directory of the document
    #location, Match the URI requested by the client through the specified pattern
    location/{#site specific location
    }
    location/admin/{#specific location of the site #
      alias/var/www/locked /;#Can only be placed in the location section, providing an alias for the specified path
    }
    #Operator, it has nothing to do with the definition order when matching
    location =/abcd {#exact match,Can't use regular
    }
    location/abc/{#url must start with the specified pattern,Can't use regular
    }
    location ^ ~/abcd ${#Wu Peugeot,uri positioning must start with a specified pattern,If it matches,Stop searching for other modes
    }
    location ~ ^/abcd ${#Regular match,Case sensitive
    }
    location ~ * ^/abcd ${#Regular match,not case sensitive
    }
    location @test {#Define the location section name, the client cannot access,Internally generated requests can,E.g. try_files or error_page
    }
  }
}
Module

ModularThe real charm of nginx is its modules,The entire application is built on a modular system,At compile time,Can be enabled or disabled for each module

index moduleDefine which index page to go back to

index index.php index.html /data/website/index.html;

#Can specify multiple,But ngxin provided the first file found

log moduleaccess_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 moduleThe default compilation nginx does not include this module

When a user request is forwarded through nginx,The application that receives the request must get the user's real ip (the server's ip is obtained after forwarding)

real_ip_header x-forwarded-for;

access moduleYou can disable the IP segment

grammar

#If there are conflicts between rules,The rule that matches first will prevail
deny ip;
deny subnet;
allow ip;
allow subnet;
#block all ips
deny all;
#allow all ips
allow all;

Configure a blockips.conf and include it in nginx.conf

e.g

location {
  allow 127.0.0.1;#Allow local IP to pay attention to the order,allow should be put in front
  deny all;#Prohibit other IP
}

rewrite moduleRole:Perform URL redirection, allowing you to remove malicious URLs, including multiple parameters (modify)

Using regular matching,Grouping and quoting,Achieve their goals

break/return/set, etc.

if (-f $uri) {
  break
}
if ($uri ~ ^/admin /) {
  return 403;
}
if ($uri ~ ^/search /(.*)$) {
  set $query $1;
  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

rewrite a b option;

options:

last:Rewrite is complete

break:After this rule is matched,Terminate the match,No longer match later rules

redirect:returns a 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 moduleThe default module,Allows you to talk to the client's http request to the backend server

location/{
  proxy_pass_header server;#This directive forces some ignored headers to be passed to the client
  proxy_redirect off;#Allows rewriting URLs that appear in the http header but are triggered by the backend server, without doing any processing to the corresponding itself
  proxy_set_header host $http_host;#Allows you to redefine the proxy header value before going to the back-end server.
The target server can see the client's original host name
  proxy_set_header x-real-ip $remote_addr;#The target server can see the real IP of the client, not the IP of the forwarding server
  proxy_set_header x-scheme $scheme;
  proxy_pass http://localhost:8080;
}

upstream module

upstream up_name {
  server 192.168.0.1:9000 weight=5;#WEIGHT
  server 192.168.0.2:9000 weight=5 max_fails=5 fail_timeout=60s;#In 60s, its error communication is more than 5 times, the service is considered invalid
  server 192.168.0.3:9000 down;#Service marked as offline,No longer use
  server 192.168.0.4:9000 backup;#Backup server,All others are down before they are enabled
}

other

Configure a static directory

 location/static /
  {
    root/var/www/app /;
    autoindex off;
  }

Load balancing

http {
  include mime.types;
  default_type application/octet-stream;
  keepalive_timeout 120;
  tcp_nodelay on;
  upstream up_localhost {
    server 127.0.0.1:8000 weight=5;
    server 127.0.0.1:8001 weight=10;
  }
  server {
    listen 80;
    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;

nginx built-in variables$arg_parameter This variable contains the value of get request parameter in the query string.

$args This variable is equal to the parameters in the request line.

$binary_remote_addr The client address in binary code.

$body_bytes_sent

$content_length The content-length field in the request header.

$content_type The content-type field in the request header.

$cookie_cookie cookie cookie value.

$document_root currently requests the value specified in the root directive.

$document_uri is the same as $uri.

$host the host header field in the request,If the host header in the request is not available,The name of the server where the server processed the request.

$is_args If $args is set, the value is "?", otherwise "".

$limit_rate This variable can limit the connection rate.

$nginx_version The version of nginx currently running.

$query_string is the same as $args.

$remote_addr IP address of the client.

$remote_port The port of the client.

$remote_user The username that has been authenticated by the auth basic module.

$request_filename the file path of the current connection request,Generated by root or alias instructions and uri requests.

$request_body This variable (0.7.58+) contains the main information of the request.It makes more sense in locations that use proxy_pass or fastcgi_pass instructions.

$request_body_file The temporary file name of the client requesting body information.

$request_completion request completed

$request_method This variable is the action requested by the client.This is usually get or post. Including 0.8.20 and before,This variable is always the action in the main request,If the current request is a subrequest,Do not use this currently requested action.

$request_uri This variable is equal to the original uri containing some client request parameters. It cannot be modified.See $uri change or rewrite uri.

$schemehttp method (such as http, https). Use as needed,example:

rewrite ^ (. +) $$scheme://example.com$1 redirect;

$server_addr server address,This value can be determined after completing a system call,If i want to bypass the system call,You must specify the address in listen and use the bind parameter.

$server_name The server name.

$server_port The port number of the request to the server.

$server_protocol The protocol used by the request,This is usually http/1.0 or http/1.1.

$uri The current uri in the request (without request parameters,The parameter is in $args), which can be different from the value of $request_uri passed by the browser, it can be redirected internally,Or use the index command to modify it.

Use separate directories, Then include specific configuration

table of Contents

nginx.conf
site /
  a.conf
  b.conf
nginx.conf
http {
  .......
  include /etc/nginx/conf.d/*.conf;
  include sites/*. conf;
}

gzip onAdd to the http module, enable gzip, note that gzip_types is configured as 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 application/font- woff;
  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;
  }

Can set timeout

   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;
}

returnReturn directly

grammar

return http_code;
return http_code "content";

e.g.

location/api/test/{
  return 403;
}
location/stat/{
  return 204;
}
location/ping/{
  return 200;
}

for mobileMobile and website 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 | 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 $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 | \-[aw]) | 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 | \-[aw]) | 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 (\-|) 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 balancingnginx.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

centos service cmds

Check the correctness of the configuration file

service nginx configtest

Reload configuration

service nginx reload
  • Previous Method for implementing verification code by jsp + Servlet programming
  • Next Jquery verify mailbox format is correct