Nginx Server Initial basic Configuration guide _nginx

Source: Internet
Author: User
Tags chmod epoll mkdir prepare nginx server

First, prepare
Pcre, for regular expression matching; zlib, for compression. This is not to elaborate, if you want to install the most simple version of the Nginx, remember to prepare these two things good.
It's dangerous to start a service with the root account! Some time ago, the test server was hacked, after all, through a root service to upload the Trojan, and finally even SSH shielding, living into a chicken ...
So, the bitter experience tells me, must establish the corresponding group and the user for the service, limits the access permission, reduces the risk!
Here, set up a WWW group for nginx and set up a login account Nginx:

#追加一个www组 
groupadd-f www 
#追加一个nginx用户 
useradd-s/sbin/nologin-g www nginx 


Create a directory to hold the Nginx log file and give the appropriate permissions:

#建立nginx日志目录 
mkdir/var/log/nginx 
#赋予访问权限 
chown Nginx.www/var/log/nginx 


Ii. Compiling and installing
I put the pcre, Zlib, nginx of the compressed packets are placed in the/opt/software path, services to be installed in the/opt/servers path.
First unpack the Pcre, zlib, Nginx, and then compile the installation:

./configure--prefix=/opt/servers/nginx \ 
--user=nginx \ 
--group=www \ 
--pid-path=/var/run/nginx.pid \ 
--error-log-path=/var/log/nginx/error.log \ 
--http-log-path=/var/log/nginx/access.log \ 
--with-pcre =/opt/software/pcre-8.10 \ 
--with-zlib=/opt/software/zlib-1.2.5 \ 
--with-http_stub_status_module \-- 
With-http_realip_module \ 
--with-http_gzip_static_module \ 
--without-http_fastcgi_module \-- 
Without-http_memcached_module \ 
--without-http_map_module \ 
--without-http_geo_module \-- 
Without-http_autoindex_module \ 
--with-poll_module 
&& make && make install 


third, System configuration
I want Nginx to be able to start or stop as a service by using service commands.
The advantage of this is that no matter what user I use to invoke this service command, it will not cause security problems with the wrong account.
Create a System file:

Vim/etc/init.d/nginx 


Masarica, Horong. The old bird has done it. Startup profile:

#!/bin/bash # v.0.0.1 # Create by Jackbillow at 2007.10.15 # nginx-this shell script takes care of starting and stop 
Ping Nginx. # chkconfig:-# Description:nginx [engine x] is light HTTP web/proxy server # that answers incoming FTP servi 
CE requests. # processname:nginx # config:/etc/nginx.conf nginx_path= "/opt/servers/nginx" nginx_pid= "/var/run/nginx.pid" # Sour 
Ce function Library. . 
/etc/rc.d/init.d/functions # Source Networking configuration. . 
/etc/sysconfig/network # Check that networking are up. [${networking} = "No"] && exit 0 [-x $nginx _path/sbin/nginx] | | 
Exit 0 retval=0 prog= "nginx" Start () {# start daemons. If [-e $nginx _pid-a!-Z $nginx _pid];then echo "Nginx already running ..." Exit 1 fi if [-E $nginx _path/conf/n ginx.conf];then echo-n $ "Starting $prog:" $nginx _path/sbin/nginx-c $nginx _path/conf/nginx.conf & retval=$ 
  ? 
    [$RETVAL-eq 0] && {touch/var/lock/subsys/$progSuccess $ "$prog"} echo Else retval=1 fi return $RETVAL} # Stop daemons. 
  Stop () {echo-n $ "stopping $prog:" killproc-d $nigx _path/sbin/nginx retval=$? 
echo [$RETVAL = 0] && rm-f $nginx _pid/var/lock/subsys/$prog} # How we were called. 
Case "in Start" start;; 
stop) stop;; 
restart) stop start;; 
  Status $prog retval=$? 
;; 
 * echo $ "Usage: $ {Start|stop|restart|status}" Exit 1 Esac Exit $RETVAL


Note that the path here:
Reference

Nginx_path= "/opt/servers/nginx" 
nginx_pid= "/var/run/nginx.pid" 


If your Nginx installation path is in another location, please change it accordingly!
The file is then given permission to execute:

chmod +x/etc/init.d/nginx 


Append to System services:

Chkconfig--add nginx 
chkconfig nginx on 


Now can be used, such as the next command to control the Nginx service!
Reference

#启动nginx 
service nginx start 
#停止nginx 
service nginx stop 
#重启nginx 
service nginx Restart 
#查看nginx状态 
Service nginx Status 


Four, the basic configuration
after the completion of the above work, nginx can not be anxious to put into use, need to do some basic configuration and optimization work.
To modify the Nginx configuration file:

Vim/opt/servers/nginx/conf/nginx.conf 

Fine tune
Reference

#使用的用户和组, we have created a new Nginx account and www workgroup user Nginx www for nginx services. 
#制定的工作衍生进程数 (twice times the number of CPU cores) Worker_processes 4; 
#错误日志存放路径, log level from low to high [Debug | info | notice | warn | error | crit] Error_log/var/log/nginx/error.log crit; 
The #指定文件描述符数量 is consistent with the Ulimit-n value work_rlimit_nofile 65535; 
Events {#使用的网络I/O model, Linux with Epoll model, UNIX using Kqueue model use Epoll; 
#允许的连接数 worker_connections 51200; 
 } http{include mime.types; 
 Default_type Application/octet-stream; #追加 ' $sent _http_cache_control ' "$sent _http_pl" "$request _time" ' Get request details Log_format main ' $remote _addr-$remote _user [ $time _local] "$request" $status $body _bytes_sent "$http _referer" "$http _user_agent" "$http _x_forwarded 
 "_for" "$sent _http_cache_control" "$sent _http_pl" "$request _time"; 
 Access_log/var/log/nginx/access.log main; 
   ... server{. location/{root HTML; 
   Index index.html index.htm index.jsp index.do; 
   #在header中传递请求放host, IP and other information proxy_set_header Host $host; Proxy_set_header x-real-IP $remote _addr; 
   Proxy_set_header x-forwarded-for $proxy _add_x_forwarded_for; 
   Proxy_pass_header Content-type; 
   Proxy_pass_header content-disposition; 
   Proxy_pass_header content-length; 
 ... 
  } 

 } 
}


v. Virtual directory
nginx Configuration Virtual directory is very simple, mainly using the root, alias two instructions.
For example, to access a picture service:
Root, for relative paths
Reference

  location/image/{ 
    root/data; 
  } 

When we visit the "/image/" path, we actually access the "/data/image/" and notice that "/data" is not followed by "/"
Alias, for Absolute path
Reference

  location/image/{ 
    alias/data/img/; 
  } 

When we access the "/image/" path, we actually access "/data/img/", noting that "/data/img/" ends with "/".

Six, redirect
Sometimes the link is not considered to put out, suddenly need to adjust the day, and can not recall the released link address in time. Had to modify the Nginx configuration.
For example, let out the link:/activity.do?m=v want it to point to/path:
Reference

Rewrite ^/activity (. *) $/last;


Want to bring the requested parameter also:
Reference

Rewrite ^/activity (. *) $/$1 last;


This is the first argument, and so on.


vi. Monitoring
Reference

  Location/status { 
   stub_status on; 
   Access_log off; 
   Allow 10.10.0.0/16; 
   Allow 10.1.0.0/16; 
   Allow 10.11.0.0/16; 

   Deny all; 
  }


Reference

Active connections:14 
Server accepts handled requests 302 reading:0 Writing:3 waiting:11 
 


Seven, log segmentation

#!/bin/bash 
# This script run in 00:00 
# author Dongliang at 2012-09-07 
# Nginx Log Path 
logs_path= '/var/l og/nginx/" 
# nginx PID Path 
nginx_pid="/var/run/nginx.pid " 
 
mkdir-p ${logs_path}$ (date-d" Yesterday "+"%Y ")/$ (date-d" Yesterday "+"%m ")/ 
 
mv ${logs_path}access.log ${logs_path}$ (date-d" Yesterday "+"%Y ")/$ (date-d" Yesterday "+"%m ")/access_$ (date-d" Yesterday "+"%y%m% 
D "). Log 
 
mv ${logs_path}error.log ${logs_path}$ (Date- D "Yesterday" + "%Y")/$ (date-d "Yesterday" + "%m")/error_$ (date-d "Yesterday" + "%y%m%d" 
). Log 
 
KILL-USR1 ' cat $ Nginx_pid ' 


Give execution permission

chmod +x nginx_log.sh 

Morning execution

CRONTAB-E 
0 0 * * */opt/script/nginx_log.sh 

Eight, nginx load balance
in http{...} To configure a upstream{...}, refer to the following:
Reference

 Upstream Tomcat { 
  server 10.11.155.26:8080; 
  Server 10.11.155.41:8080; 
 } 

Then modify the location node and configure the agent:
Reference

Location/{ 
  ... 
   Proxy_pass Http://tomcat; 

  ... 
}

When accessing the root path, the carousel is routed to two servers, and the back-end server is Tomcat or jetty and so on, it doesn't matter, divert.
Of course, some machines have good performance, or low load, can bear high load access, you can through the weight (weight), improve access frequency. The higher the number, the more requests are allocated.
The server directive parameters are as follows:
weight--weight, the larger the number, the more requests are divided, the default value is 1.
max_fails--the number of attempts to access a failed back-end server. The default value is 1, and checking is turned off when set to 0 o'clock.
fail_timeout--the expiration timeout, pausing access to the node after multiple access failures.
The down--flag server is permanently offline and is used for ip_hash directives.
backup--is enabled only if the non-backup server is all down or busy.

For example, you can configure this:
Reference

 Upstream Tomcat { 
  server 10.11.155.26:8080 weight=5; 
  Server 10.11.155.41:8080 weight=10; 
 } 

The latter will have a higher number of requests.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.