Nginx installation, Default virtual host, user authentication, nginx PHP parsing

Source: Internet
Author: User
Tags epoll fpm sendfile

12.6 Nginx Installation

Preparatory work

Install package

[email protected] ~]# cd/usr/local/src/

To download the installation package:
[email protected] src]# wget

[email protected] src]# Tar zxvf nginx-1.12.1.tar.gz


Environment configuration

[email protected] src]# CD NGINX-1.12.1/

[email protected] Nginx-1.12.1]#/configure--prefix=/usr/local/nginx
#如果需要支持某模块, can be added here, such as https, ssl, etc.
Compile & Install

[[email protected] nginx-1.12.1]# make && make install
[[email protected] nginx-1.12.1]# Echo $?

[email protected] nginx-1.12.1]# cd/usr/local/nginx/
[[email protected] nginx]# ls
Conf HTML logs Sbin


Add & Start Service

To create a startup script:
[email protected] nginx]# Vim/etc/init.d/nginx

Chkconfig:-21description:http Service. Source Function Library

. /etc/init.d/functions

Nginx Settings

nginx_sbin= "/usr/local/nginx/sbin/nginx"
nginx_conf= "/usr/local/nginx/conf/nginx.conf"
Nginx_pid= "/usr/local/nginx/logs/"
prog= "Nginx"
Start ()
Echo-n $ "starting $prog:"
Daemon $NGINX _sbin-c $NGINX _conf
Return $RETVAL
Stop ()
Echo-n $ "stopping $prog:"
Killproc-p $NGINX _pid $NGINX _sbin-term
Return $RETVAL
Reload ()
Echo-n $ "reloading $prog:"
Killproc-p $NGINX _pid $NGINX _sbin-hup
Return $RETVAL
Restart ()
Configtest ()
$NGINX _sbin-c $NGINX _conf-t
return 0
Case "$" in
echo $ "Usage: $ {start|stop|reload|restart|configtest}"

Check Script syntax:
[email protected] nginx]#/usr/local/nginx/sbin/nginx-t
Nginx:the configuration file/usr/local/nginx/conf/nginx.conf syntax is OK
Nginx:configuration file/usr/local/nginx/conf/nginx.conf Test is successful

To change permissions:
[email protected] nginx]# chmod 755/etc/init.d/nginx

Add to System service:
[email protected] nginx]# Chkconfig--add nginx
[[email protected] nginx]# chkconfig nginx on

Change the configuration file

[email protected] nginx]# cd/usr/local/nginx/conf/

Comment out the Nginx script to create your own script:
[email protected] conf]# MV nginx.conf Nginx.conf.bak

[email protected] conf]# Vim nginx.conf

User Nobody nobody;
Worker_processes 2;
Error_log/usr/local/nginx/logs/nginx_error.log crit;
Worker_rlimit_nofile 51200;
Use epoll;
Worker_connections 6000;

Include mime.types;
Default_type application/octet-stream;
Server_names_hash_bucket_size 3526;
Server_names_hash_max_size 4096;
Log_format combined_realip ' $remote _addr $http _x_forwarded_for [$time _local] '
' $host ' $request _uri "$status"
' "$http _referer" "$http _user_agent";
Sendfile on;
Tcp_nopush on;
Keepalive_timeout 30;
Client_header_timeout 3m;
Client_body_timeout 3m;
Send_timeout 3m;
Connection_pool_size 256;
Client_header_buffer_size 1k;
Large_client_header_buffers 8 4k;
Request_pool_size 4k;
Output_buffers 4 32k;
Postpone_output 1460;
Client_max_body_size 10m;
Client_body_buffer_size 256k;
Fastcgi_intercept_errors on;
Tcp_nodelay on;
Gzip on;
Gzip_min_length 1k;
Gzip_buffers 4 8k;
Gzip_comp_level 5;
Gzip_http_version 1.1;
Gzip_types text/plain application/x-javascript text/css text/htm
Listen 80;
server_name localhost;
Index index.html index.htm index.php;
Location ~. php$
Include fastcgi_params;
Fastcgi_pass unix:/tmp/php-fcgi.sock;
Fastcgi_index index.php;
Fastcgi_param script_filename/usr/local/nginx/html$fastcgi_script_name;

Detection syntax:
[email protected] conf]#/usr/local/nginx/sbin/nginx-t
Nginx:the configuration file/usr/local/nginx/conf/nginx.conf syntax is OK
Nginx:configuration file/usr/local/nginx/conf/nginx.conf Test is successful

To start the Nginx service:
[[email protected] Conf]#/etc/init.d/nginx Start
Starting Nginx (via systemctl): [ok]

At this point, nginx basic configuration is complete!


[[email protected] conf]# Curl localhost
<! DOCTYPE html>
<title>welcome to Nginx!</title>
Body {
margin:0 auto;
font-family:tahoma, Verdana, Arial, sans-serif;
<p>if you see this page, the Nginx Web server is successfully installed and
Working. Further configuration is required.</p>

<p>for online documentation and support for refer to
<a href= "" ></a>.<br/>
Commercial support was available at
<a href= "" ></a>.</p>

<p><em>thank for using nginx.</em></p>
Using browser detection:

First add the virtual host IP to the local hosts and then Access:

Detecting PHP parsing

[email protected] conf]# vim/usr/local/nginx/html/1.php
echo "welcom to Adai-nginx text.";

[email protected] conf]# Curl localhost/1.php
Welcom to Adai-nginx Text.
Browser detection:


Common 502 Problem Solving

For lnmp, the most common is the 502 problem, LNMP environment after the completion of a visit to the site directly prompted "502 bad Gateway". The main reasons are broadly divided into two types:

(1) Configuration Error

There is a section in Nginx configuration:

Location ~. php$
Include fastcgi_params;
Fastcgi_pass unix:/tmp/php-fcgi.sock;
Fastcgi_index index.php;
Fastcgi_param script_filename/usr/local/nginx/html$fastcgi_script_name;
If the Fastcgi_pass (this is used to Communicate) after the specified path configuration is wrong, then there will be a 502 error, because Nginx can not find php-fpm, fastcgi _pass back with the socket can also follow ip:port, The default listener address Is:
Note: here are two forms can be, but two configuration files (nginx and Php-fpm) in the form must be unified, or absolute 502; if you use socket form, the path of the socket file must be right, otherwise it is still 502.

(2) Resource Exhaustion

LNMP Architecture Processing php, is the nginx directly to the back end of the php-fpm service, if the Nginx request volume is high, and we did not give php-fpm to configure enough child processes, then there is always php-fpm resources exhausted, Once the PHP-FPM is exhausted, it can also cause 502 errors to Occur. The solution is to adjust the Pm.max_children value in the php-fpm.conf to make it increase. however, there is no limit to the increase because the server has limited resources. 4G Memory Machine If only run PHP-FPM and nginx, do not run the MySQL service, pm.max _children can be set to 150, try not to exceed the value, 8G memory is set to 300, and so On.

(3) Listen.mode

There is a parameter Listen.mode in the PHP-FPM configuration file that specifies the socket file that PHP-FPM listens to listen =/tmp/ Php-fcgi.sock permissions, If you do not specify permissions, the default permissions are 440 (only allow root user and root group to read), and then listen to the file in Nginx will be prompted 502 error, the solution is to give socket file read and Write permissions 666.

If you encounter other rare errors, we can modify the level of Nginx error log (/usr/local/nginx/logs/nginx_error.log), in the configuration file/usr/local/nginx/conf/ Nginx.conf the crit to debug, so that it records the most log content, so that we are easy to troubleshoot errors, but the configuration changes to remember to change the level back to crit, to avoid the log files occupy too much disk space.

12.7 nginx Default Virtual host

Edit the nginx configuration file, Delete the original server content, add the following content:

Create a virtual host

Add a virtual Host directory

[email protected] ~]# cd/usr/local/nginx/conf
[email protected] conf]# vim/usr/local/nginx/conf/nginx.conf
Include vhost/*.conf;
#创建一个虚拟主机配置文件子目录 (equivalent to adding a child virtual Host)

To create a directory file in a configuration file:
[email protected] conf]# mkdir vhost
Note: the "include" syntax is supported in the "nginx.conf" File.

Add a virtual machine host:

[email protected] conf]# CD vhost

[email protected] vhost]# Vim

Listen default_server;
The default virtual host is marked #有 ' Default_server '
Index index.html index.htm index.php;

Create the root directory specified in the configuration file:
[email protected] vhost]# Mkdir-p/data/wwwroot/default
Add content to a virtual host

To enter the directory, add the index page:
[email protected] vhost]# Cd/data/wwwroot/default

[email protected] default]# Vim index.html

This is the default Directory.

[email protected] default]#/usr/local/nginx/sbin/nginx-t
Nginx:the configuration file/usr/local/nginx/conf/nginx.conf syntax is OK
Nginx:configuration file/usr/local/nginx/conf/nginx.conf Test is successful

Reboot or reload (select one):
[email protected] Default]#/usr/local/nginx/sbin/nginx-s Reload
[email protected] Default]#/usr/local/nginx/sbin/nginx Restart

[[email protected] default]# Curl localhost
This is the default Directory.

That is: add a virtual host, the so-called default virtual host is The/usr/local/nginx/conf/vhost directory in the virtual host configuration file with "default_server" tag of the virtual Host.

12.8 Nginx user authentication

Create a virtual machine host:

Operating in the Vhost directory:
[email protected] vhost]# Vim

Listen 80;
Index index.html index.htm index.php;

Auth_basic "auth";
Note: the above "location" in the content is to set up user Authentication. This is the user authentication for the entire site, if only for a directory set user authentication, in the location of the row for editing, such as: location/admin directory. You can also set up a user authentication for a request (that is, a normal file), such as location ~ admin.php () using ~ for matching).

Create a password file

You need to use the APACHE/USR/LOCAL/APACHE/BIN/HTPASSWD command here, if the machine already has apache, you can use it directly, if not, you need to install the httpd command with Yum:

[email protected] vhost]# Yum install-y httpd
To create a password file:

[email protected] vhost]# htpasswd-c/usr/local/nginx/conf/htpasswd Adai
New password:
Re-type New Password:
Adding Password for user Adai
That is, create the password file htpasswd, specifying the user as Adai. '-c ' =create, Create the password file, if the user is added the second time, do not add the option, the added user name and password will be saved to the File.


[email protected] vhost]#/usr/local/nginx/sbin/nginx-t
Nginx:the configuration file/usr/local/nginx/conf/nginx.conf syntax is OK
Nginx:configuration file/usr/local/nginx/conf/nginx.conf Test is successful
[email protected] Vhost]#/usr/local/nginx/sbin/nginx-s Reload
Description: the advantage of using reload instead of restart is to avoid errors in the configuration file and not start properly! Reload does not disrupt the original operating Environment.

Add the specified directory

Add the root directory specified by the virtual host configuration File:
[email protected] vhost]# mkdir/data/wwwroot/

To add an index page:
[email protected] vhost]# Echo "this is" >/data/wwwroot/

[email protected] vhost]# curl-x127.0.0.1:80
This is
Note: If you do not specify a user name and password, the error 401 (user authentication required), if the root of the virtual host will be created error 404 (the specified directory is not found), if the specified directory does not add an index page (. html or. php file) will error 404 (file error).


Configure Virtual host PHP parsing:

To edit the configuration file, add the following location content:

[email protected] vhost]# vim/usr/local/nginx/conf/vhost/

location ~ \.php$    #配置PHP解析    {        include fastcgi_params;        fastcgi_pass unix:/tmp/php-fcgi.sock;        fastcgi_index index.php;        fastcgi_param SCRIPT_FILENAME /data/wwwroot/$fastcgi_script_name;    }

Note: "fastcgi_param script_filename" The line path is consistent with the site root path,



[email protected] vhost]# curl-x127.0.0.1:80
This is a test of. PHP
Note: in order to facilitate the detection, the user authentication has been turned off.

12.9 Nginx Domain Redirection

To edit a virtual host configuration file:

[email protected] vhost]# Vim

Listen 80;
#为一个IP配置多个域名, the weight will change, so you need to enable users to access the other domain name when all jump to the first domain name
Index index.html index.htm index.php;
If ($host! = ' ') {
Rewrite ^/(. *) $$1 permanent;

[email protected] vhost]#/usr/local/nginx/sbin/nginx-t
Nginx:the configuration file/usr/local/nginx/conf/nginx.conf syntax is OK
Nginx:configuration file/usr/local/nginx/conf/nginx.conf Test is successful
[email protected] Vhost]#/usr/local/nginx/sbin/nginx-s Reload
Description: use the rewrite module for domain name redirection to achieve the domain name jump Function.


[email protected] vhost]# curl-x127.0.0.1:80
http/1.1 301 Moved Permanently
date:thu, 10:41:30 GMT
That is, 301: permanent domain jump, the address after the jump is: location:

Extension: nginx configuration file

User www www;

#nginx进程数, the recommended setting is equal to the total CPU core Number.
Worker_processes 8;

#全局错误日志定义类型, [debug | info | notice | warn | error | crit]
Error_log/var/log/nginx/error.log info;


#一个nginx进程打开的最多文件描述符数目, The theoretical value should be the number of open files (the value of the system Ulimit-n) and the number of Nginx processes, but the Nginx allocation request is not uniform, so the recommendation is consistent with the value of Ulimit-n.
Worker_rlimit_nofile 65535;

#参考事件模型, use [kqueue | rtsig | epoll |/dev/poll | select | poll]; The Epoll model is a high-performance network I/O model in the Linux version 2.6 kernel, and if it runs on freebsd, it uses the Kqueue model.
Use epoll;
#单个进程最大连接数 (maximum Number of connections = number of connections * processes)
Worker_connections 65535;

Include mime.types; #文件扩展名与文件类型映射表
Default_type application/octet-stream; #默认文件类型
#charset utf-8; #默认编码
Server_names_hash_bucket_size 128; #服务器名字的hash表大小
Client_header_buffer_size 32k; #上传文件大小限制
Large_client_header_buffers 4 64k; #设定请求缓
Client_max_body_size 8m; #设定请求缓
Sendfile on; #开启高效文件传输模式, The sendfile instruction specifies whether Nginx calls the Sendfile function to output the file, and for normal applications to be set to on, if it is used for downloading applications such as disk IO heavy load applications, can be off to balance disk and network I/O processing speed, Reduce the load on the System. Note: If the picture does not appear normal, change this to off.
AutoIndex on; #开启目录列表访问, the appropriate download server, the default Shutdown.
Tcp_nopush on; #防止网络阻塞
Tcp_nodelay on; #防止网络阻塞
Keepalive_timeout 120; #长连接超时时间, Unit is seconds

#FastCGI相关参数是为了改善网站的性能: reduce resource usage and improve access Speed. The following parameters can be understood by literal means.
Fastcgi_connect_timeout 300;
Fastcgi_send_timeout 300;
Fastcgi_read_timeout 300;
Fastcgi_buffer_size 64k;
Fastcgi_buffers 4 64k;
Fastcgi_busy_buffers_size 128k;
Fastcgi_temp_file_write_size 128k;

Gzip on; #开启gzip压缩输出
Gzip_min_length 1k; #最小压缩文件大小
Gzip_buffers 4 16k; #压缩缓冲区
Gzip_http_version 1.0; #压缩版本 (default 1.1, Front End If squid2.5 please use 1.0)
Gzip_comp_level 2; #压缩等级
Gzip_types text/plain application/x-javascript text/css application/xml;
#压缩类型, The default is already included text/html, so there is no need to write, write up will not have a problem, but there will be a warn.
Gzip_vary on;
#limit_zone crawler $binary _remote_addr 10m; #开启限制IP连接数的时候需要使用

Upstream {
#upstream的负载均衡, weight is a weight that can be defined based on machine Configuration. The Weigth parameter represents weights, and the higher the weight, the greater the probability of being allocated.
Server weight=3;
Server weight=2;
Server weight=3;

#域名可以有多个, separate
server_name with spaces;
Index index.html index.htm index.php;
Location ~. . (php|php5)? $
Fastcgi_index index.php;
include fastcgi.conf;
Location ~.
. (gif|jpg|jpeg|png|bmp|swf) $
expires 10d;
Location ~. *. ( js|css)? $
expires 1h;
Log_format access ' $remote _addr-$remote _user [$time _local] "$request" '
' $status $body _bytes_sent " $http _referer "'
'" $http _user_agent "$http _x_forwarded_for ';
Access_log/var/log/nginx/ha97access.log access;

#对 "/" Enable reverse proxy
Proxy_redirect off;
Proxy_set_header X-real-ip $remote _addr;
#后端的Web服务器可以通过X-forwarded-for Get the user real IP
proxy_set_header x-forwarded-for $proxy _add_x_forwarded_for;
#以下是一些反向代理的配置, Optional.
Proxy_set_header Host $host;
Client_max_body_size 10m; #允许客户端请求的最大单文件字节数
client_body_buffer_size 128k; #缓冲区代理缓冲用户端请求的最大字节数,
Proxy_ Connect_timeout 90; #nginx跟后端服务器连接超时时间 (proxy Connection Timeout)
proxy_send_timeout, #后端服务器数据回传时间 (proxy send Timeout)
proxy_read_timeout; #连接成功后, Back-end Server Response time (proxy receive Timeout)
proxy_buffer_size 4k; #设置代理服务器 (nginx) buffer size for saving user header information
Proxy_buffers 4 32k; #proxy_buffers缓冲区, The average web page is set below 32k
proxy_busy_buffers_size 64k; #高负荷下缓冲大小 (proxy_buffers*2)
proxy_temp_file_write_size 64k;
#设定缓存文件夹大小, greater than this value, the

will be passed from the upstream server

Location/nginxstatus {
Stub_status on;
Access_log on;
Auth_basic "nginxstatus";
Auth_basic_user_file conf/htpasswd;

Location ~. (jsp|jspx|do)? $ {
Proxy_set_header Host $host;
Proxy_set_header X-real-ip $remote _addr;
Proxy_set_header x-forwarded-for $proxy _add_x_forwarded_for;
Location ~. . (htm|html|gif|jpg|jpeg|png|bmp|swf|ioc|rar|zip|txt|flv|mid|doc|ppt|pdf|xls|mp3|wma) $
{expires 15d;}
Location ~
. (js|css)? $
{expires 1h;}

Nginx installation, Default virtual host, user authentication, nginx PHP parsing

Related Article

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: 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.