Nginx server installation with some basic configuration summary

  • 2020-05-14 05:41:15
  • OfStack

The installation
ubuntu under


sudo apt-get install nginx

Start the


sudo /etc/init.d/nginx start    # through init.d The startup file under is started. 
sudo service nginx start# through ubuntu The service manager is started 

Profile location


/etc/nginx/nginx.conf

Compile the installation
1. 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 the apt , you can use the download package to manually compile the installation 

2. Download package

www. nginx. net download the 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
# By default, the installation directory /usr/local/nginx
./configure
make
make install

# configuration 
./configure --conf-path=/etc/nginx/nginx.conf

You can configure some other options

Check the Configuration summary directory after installation
4. init script

You need to create an init script for nginx
From the Internet for 1, put/etc/init d/nginx
Recommended build configuration

1. Use different prefix to specify different versions and upgrade


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

Basic operation
See the help


sudo /etc/init.d/nginx start    # through init.d The startup file under is started. 
sudo service nginx start# through ubuntu The service manager is started 
0

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

Heavy load


sudo /etc/init.d/nginx start    # through init.d The startup file under is started. 
sudo service nginx start# through ubuntu The service manager is started 
3

Verify that the configuration file is correct


sudo /etc/init.d/nginx start    # through init.d The startup file under is started. 
sudo service nginx start# through ubuntu The service manager is started 
4

HTTP basic configuration
Configuration instructions
Note that #
Each instruction always ends with a point (;)
Configuration inheritance: if other extents are nested in a block, the nested extents inherit the Settings of their parent extents
String, can be without quotation marks, but if there are special characters (Spaces, semicolons, curly braces) need to be caused by quotation marks
Unit: size (k/K m/M) time value (ms/s/m/h/d/w/M/y s by default)
The module provides various variable values, which can be read and assigned (you need to check the list of variables provided by each module).
Configuration file directory structure

/usr/local/nginx/conf/

-mime.types 1 file extension list that is associated with the MIME type
-fastcgi.conf configuration files related to FastCGI
-proxy. conf configuration file related to Proxy
- basic configuration file for nginx.conf application
- sites/
|-a.conf # allows one profile to be created for each individual website
|- b.conf
|- dir/
|- c.conf

You need to use the include command in nginx.conf


sudo /etc/init.d/nginx start    # through init.d The startup file under is started. 
sudo service nginx start# through ubuntu The service manager is started 
5

Configuration file structure


sudo /etc/init.d/nginx start    # through init.d The startup file under is started. 
sudo service nginx start# through ubuntu The service manager is started 
6 The module
modular
The real beauty of nginx is its modules. The entire application is built on a modular system, and each module can be enabled or disabled at compile time

index module
Define which page to go back to, index


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

# can specify more than one, but ngxin provides the first found file
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 build nginx does not include this module

When the user request is forwarded through nginx, the application receiving the request should get the real IP of the user (IP of the server is received after forwarding).


real_ip_header X-Forwarded-For;

Access module
You can disable the ip segment

grammar


sudo /etc/init.d/nginx start    # through init.d The startup file under is started. 
sudo service nginx start# through ubuntu The service manager is started 
9

Configure 1 blockips.conf and then include in nginx.conf

e.g


location {
  allow 127.0.0.1; # Allow local ip  Notice the order, allow Put it in front 
  deny all; # Ban on other ip
}

Rewrite module
Effect: performs URL redirection, allowing you to remove malicious URL with multiple parameters (modified)

Use 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 $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 grammar


rewrite A B option;

options:
last: means finish rewrite
break: after the match of this rule is completed, the match is terminated and the subsequent rule is no longer matched
redirect: return 302 temporary redirection, the address bar will show the address after the jump
permanent: return 301 permanent redirect, the address bar will show the address after the jump
Proxy module
The default module, which allows you to request an HTTP transfer from the client to the back-end server


location / {
  proxy_pass_header Server; # This command forces 1 The ignored headers are passed to the client 
  proxy_redirect off; # Allow overwrites to appear in HTTP The header is redirected by the backend server URL, You don't do anything to the corresponding itself 
  proxy_set_header Host $http_host; # Allows you to redefine the proxy header The value is then passed 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 client's reality ip , not the forward server ip
  proxy_set_header X-Scheme $scheme;
  proxy_pass http://localhost:8080;
}

upstream module


upstream up_name {
  server 192.168.0.1:9000 weight=5; # The weight 
  server 192.168.0.2:9000 weight=5 max_fails=5 fail_timeout=60s; # in 60s Inside, its error communication exceeds 5 time , The service is considered invalid 
  server 192.168.0.3:9000 down; # The service is marked offline and no longer in use 
  server 192.168.0.4:9000 backup; # Backup server, all other down to enable 
}

other
Configure the 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;
    }
  }

}

Control 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 PARAMETER requested by GET in the query string.
The $args variable is equal to the argument in the request line.
$binary_remote_addr 2 base code client address.
$body_bytes_sent
$content_length the Content-length field in the request header.
$content_type request header Content-Type field.
$cookie_COOKIE cookie COOKIE
$document_root currently requests the value specified in the root directive.
$document_uri is the same as $uri.
The host header field in the $host request, and if the host header in the request is not available, the server name for which the request is processed for the server.
$is_args if $args is set, the value is "?" , otherwise is "".
The variable $limit_rate limits the connection rate.
$nginx_version version number of nginx currently running.
$query_string is the same as $args.
$remote_addr client IP address.
$remote_port client port.
$remote_user has been authenticated by Auth Basic Module.
The file path of the current connection request is generated by the root or alias instruction and the URI request.
The $request_body variable (0.7.58+) contains the main information for the request. This makes sense in location using the proxy_pass or fastcgi_pass directives.
$request_body_file client requests the temporary file name of the principal information.
$request_completion request completed
The variable $request_method is the action requested by the client, usually GET or POST. This variable is always the action in main request, including 0.8.20 and before. If the current request is a subrequest, the action of the current request is not used.
The variable $request_uri is equal to the original URI containing some client request parameters. It cannot be modified. Please see $uri for changing or overwriting URI.
$schemeHTTP method (e.g. http, https). Use as needed, e.g.
rewrite ^(.+)$ $scheme://example.com$1 redirect;
$server_addr server address, which you can determine after one system call, must be specified in listen and the bind parameter if you want to bypass the system call.
$server_name server name.
$server_port request arrives at the server's port number.
$server_protocol requests the protocol to be used, usually HTTP/1.0 or HTTP/1.1.
The current URI in the $uri request (without the request parameter, the parameter is located at $args) can differ from the browser-passed value of $request_uri, which can be modified by internal redirection or with the index directive.

Use a separate directory, 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 the http module and 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 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;
  }

You can set timeout times


    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 standing


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

for mobile
The mobile end and the website end 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|\-[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


centos service cmds

Check the configuration file for correctness


apt-get install libpcre3 libpcre3-dev
0


Reload configuration


apt-get install libpcre3 libpcre3-dev
1


Related articles: