目录
- 一、Nginx
- nginx应用场合
- 二、nginx服务搭建
- 1、使用apt安装
- 2、安装后的位置:
- 3、启动并验证效果
- 4、查看版本号:
- 三、nginx配置文件介绍
- 1、nginx 文件结构
- 2、默认的配置
- 3、nginx的基本配置
- 四、 nginx虚拟主机配置
- 验证配置文件:
- 五、nginx全局变量
- 六、Nginx主要配置
- 1、静态Http服务器配置
- 2、反向代理服务器配置
- 3、负载均衡配置
- 4、虚拟主机配置
一、Nginx
Nginx(Engine X)是由俄罗斯程序员Igor Sysoev开发的一款高性能Web服务器、反向代理服务器以及IMAP/POP3/SMTP代理服务器。
作为Apache、Nginx和Lighttpd三大主流WEB服务器之一,Nginx在处理高连接并发时,是Apache服务器的优秀替代方案。
nginx应用场合
- 静态服务器:适用于图片、视频等服务,也可由Lighttpd承担。能处理数万并发,支持HTML、JS、CSS、FLV、JPG、GIF等格式。
- 动态服务:通过FastCGI方式运行PHP、JSP。通常PHP并发能力在500-1500之间,MySQL并发在300-1500之间。
- 反向代理与负载均衡:当日PV低于2000万时,可直接使用Nginx进行代理处理。
- 缓存服务:功能类似于Squid和Varnish。
官方下载地址为:http://nginx.org/en/download.html
官网提供三种版本类型:
Mainline version:主线版本,即当前正在开发的版本;Stable version:最新稳定版,推荐在生产环境中使用;Legacy versions:遗留的老版本稳定版。

二、nginx服务搭建
1、使用apt安装
sudo apt install nginx
2、安装后的位置:
- /usr/sbin/nginx:主程序路径
- /etc/nginx:配置文件存放目录
- /usr/share/nginx:静态文件存放目录
- /var/log/nginx:日志文件存放目录
3、启动并验证效果
service nginx start # 启动nginx
service nginx reload # 重新加载nginx配置文件
在浏览器中输入服务器IP地址,若显示“Welcome to nginx”页面,则表明配置成功。
另外两个命令
nginx -s reopen # 重启 Nginx
nginx -s stop # 停止 Nginx

4、查看版本号:
~$ nginx -v
nginx version: nginx/1.14.0 (Ubuntu)
三、nginx配置文件介绍

1、nginx 文件结构
- 全局块:配置影响Nginx全局的指令,包括运行用户组、PID路径、日志路径、配置文件引入及Worker Process数量等。
- Events块:配置影响服务器与用户网络连接的因素,如单进程最大连接数、事件驱动模型、是否允许同时接受多个网络连接及序列化设置等。
- Http块:可嵌套多个Server,配置代理、缓存、日志定义等绝大多数功能及第三方模块,涉及文件引入、MIME-Type定义、Sendfile传输、超时时间及单连接请求数等。
- Server块:配置虚拟主机相关参数,一个Http块中可包含多个Server块。
- Location块:配置请求路由规则及各页面的具体处理逻辑。
... # 全局块。配置影响nginx全局的指令。
events { # events块。配置影响nginx服务器或与用户的网络连接。
...
}
http # http块。可以嵌套多个server,配置代理,缓存,日志定义等绝大多数功能和第三方模块的配置。
{
... # http全局块
server # server块。配置虚拟主机的相关参数,一个http中可以有多个server。
{
... # server全局块
location [PATTERN] # location块。配置请求的路由,以及各种页面的处理情况。
{
...
}
location [PATTERN]
{
...
}
}
server
{
...
}
... # http全局块
}
2、默认的配置
##
# You should look at the following URL's in order to grasp a solid understanding
# of Nginx configuration files in order to fully unleash the power of Nginx.
# https://www.nginx.com/resources/wiki/start/
# https://www.nginx.com/resources/wiki/start/topics/tutorials/config_pitfalls/
# https://wiki.debian.org/Nginx/DirectoryStructure
#
# In most cases, administrators will remove this file from sites-enabled/ and
# leave it as reference inside of sites-available where it will continue to be
# updated by the nginx packaging team.
#
# This file will automatically load configuration files provided by other
# applications, such as Drupal or Wordpress. These applications will be made
# available underneath a path with that package name, such as /drupal8.
#
# Please see /usr/share/doc/nginx-doc/examples/ for more detailed examples.
##
# Default server configuration
#
server {
listen 80 default_server;
listen [::]:80 default_server;
# SSL configuration
#
# listen 443 ssl default_server;
# listen [::]:443 ssl default_server;
#
# Note: You should disable gzip for SSL traffic.
# See: https://bugs.debian.org/773332
#
# Read up on ssl_ciphers to ensure a secure configuration.
# See: https://bugs.debian.org/765782
#
# Self signed certs generated by the ssl-cert package
# Don't use them in a production server!
#
# include snippets/snakeoil.conf;
root /var/www/html;
# Add index.php to the list if you are using PHP
index index.html index.htm index.nginx-debian.html;
server_name _;
location / {
# First attempt to serve request as file, then
# as directory, then fall back to displaying a 404.
try_files $uri $uri/ =404;
}
# pass PHP scripts to FastCGI server
#
#location ~ \.php$ {
# include snippets/fastcgi-php.conf;
#
# # With php-fpm (or other unix sockets):
# fastcgi_pass unix:/var/run/php/php7.0-fpm.sock;
# # With php-cgi (or other tcp sockets):
# fastcgi_pass 127.0.0.1:9000;
#}
# deny access to .htaccess files, if Apache's document root
# concurs with nginx's one
#
#location ~ /\.ht {
# deny all;
#}
}
# Virtual Host configuration for example.com
#
# You can move that to a different file under sites-available/ and symlink that
# to sites-enabled/ to enable it.
#
#server {
# listen 80;
# listen [::]:80;
#
# server_name example.com;
#
# root /var/www/example.com;
# index index.html;
#
# location / {
# try_files $uri $uri/ =404;
# }
#}
3、nginx的基本配置
########### 每个指令必须有分号结束。#################
#user administrator administrators; #配置用户或者组,默认为nobody nobody。
#worker_processes 2; #允许生成的进程数,默认为1
#pid /nginx/pid/nginx.pid; #指定nginx进程运行文件存放地址
error_log log/error.log debug; #制定日志路径,级别。这个设置可以放入全局块,http块,server块,级别以此为:debug|info|notice|warn|error|crit|alert|emerg
events {
accept_mutex on; #设置网路连接序列化,防止惊群现象发生,默认为on
multi_accept on; #设置一个进程是否同时接受多个网络连接,默认为off
#use epoll; #事件驱动模型,select|poll|kqueue|epoll|resig|/dev/poll|eventport
worker_connections 1024; #最大连接数,默认为512
}
http {
include mime.types; #文件扩展名与文件类型映射表
default_type application/octet-stream; #默认文件类型,默认为text/plain
#access_log off; #取消服务日志
log_format myFormat '$remote_addr–$remote_user [$time_local] $request $status $body_bytes_sent $http_referer $http_user_agent $http_x_forwarded_for'; #自定义格式
access_log log/access.log myFormat; #combined为日志格式的默认值
sendfile on; #允许sendfile方式传输文件,默认为off,可以在http块,server块,location块。
sendfile_max_chunk 100k; #每个进程每次调用传输数量不能大于设定的值,默认为0,即不设上限。
keepalive_timeout 65; #连接超时时间,默认为75s,可以在http,server,location块。
upstream mysvr {
server 127.0.0.1:7878;
server 192.168.10.121:3333 backup; #热备
}
error_page 404 https://www.baidu.com; #错误页
server {
keepalive_requests 120; #单连接请求上限次数。
listen 80; #监听端口
server_name 127.0.0.1; #监听地址
location ~*^.+$ { #请求的url过滤,正则匹配,~为区分大小写,~*为不区分大小写。
#root path; #根目录
#index vv.txt; #设置默认页
proxy_pass http://mysvr; #请求转向mysvr 定义的服务器列表
deny 127.0.0.1; #拒绝的ip
allow 172.18.5.54; #允许的ip
}
}
}
四、 nginx虚拟主机配置
#下面是server虚拟主机的配置段
server
{
listen 80;#监听端口
server_name localhost;#域名
index index.html index.htm index.php;
root /usr/local/webserver/nginx/html;#站点目录
location ~ .*\.(php|php5)?$
{
#fastcgi_pass unix:/tmp/php-cgi.sock;
fastcgi_pass 127.0.0.1:9000;
fastcgi_index index.php;
include fastcgi.conf;
}
location ~ .*\.(gif|jpg|jpeg|png|bmp|swf|ico)$
{
expires 30d;
#access_log off;
}
location ~ .*\.(js|css)?$
{
expires 15d;
#access_log off;
}
access_log off;
}
验证配置文件:
root@ubuntu: nginx -t
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful
五、nginx全局变量
- $remote_addr 与 $http_x_forwarded_for:用于记录客户端IP地址。
- $remote_user:用于记录客户端用户名称。
- $time_local:用于记录访问时间与时区。
- $request:用于记录请求的URL与HTTP协议。
- $status:用于记录请求状态,成功时为200。
- $body_bytes_sent:记录发送给客户端的文件主体内容大小。
- $http_referer:用于记录从哪个页面链接访问过来。
- $http_user_agent:记录客户端浏览器的相关信息。
访问链接是:http://localhost:88/test1/test.php
网站路径是:/var/www/html
$host:localhost
$server_port:88
$request_uri:http://localhost:88/test1/test.php
$document_uri:/test1/test.php
$document_root:/var/www/html
$request_filename:/var/www/html/test1/test.php
六、Nginx主要配置
1、静态Http服务器配置
Nginx作为HTTP服务器,可将服务器上的静态文件(如HTML、图片)通过HTTP协议展示给客户端。配置方法如下:
server {
listen 80; # 端口
server_name localhost 192.168.1.100; # 域名
location / { # 代表这是项目根目录
root /usr/share/nginx/www; # 虚拟目录
}
}
2、反向代理服务器配置
反向代理概念:原本客户端可直接通过HTTP访问应用服务器,若在中间加入Nginx,客户端请求Nginx,Nginx再请求应用服务器并将结果返回,此时Nginx即为反向代理服务器。

反向代理配置:
server {
listen 80;
location / {
proxy_pass http://192.168.0.112:8080; # 应用服务器HTTP地址
}
}
既然服务器可直接HTTP访问,为何要增加反向代理?这并非多此一举。反向代理不仅实现负载均衡和虚拟主机功能,还具备其他重要作用,详见下文。
3、负载均衡配置
当网站访问量巨大导致单台服务器性能不足时,可将相同应用部署在多台服务器上,将大量用户请求分配给不同机器处理。此举既提升速度,又增强容错性:只要有一台服务器正常运行,用户即可正常访问。Nginx可通过反向代理实现负载均衡。

负载均衡配置:
upstream myapp {
server 192.168.0.111:8080; # 应用服务器1
server 192.168.0.112:8080; # 应用服务器2
}
server {
listen 80;
location / {
proxy_pass http://myweb;
}
}
4、虚拟主机配置
部分网站因访问量小需节省成本,可将多个网站部署在同一台服务器上。例如将www.aaa.com和www.bbb.com部署于同一服务器,域名解析至同一IP,但用户通过不同域名可访问完全不同的网站,互不干扰,如同访问独立服务器,故称为虚拟主机。
虚拟主机配置:
server {
listen 80 default_server;
server_name _;
return 444; # 过滤其他域名的请求,返回444状态码
}
server {
listen 80;
server_name www.aaa.com; # www.aaa.com域名
location / {
proxy_pass http://localhost:8080; # 对应端口号8080
}
}
server {
listen 80;
server_name www.bbb.com; # www.bbb.com域名
location / {
proxy_pass http://localhost:8081; # 对应端口号8081
}
}
在服务器8080和8081端口分别开启应用,客户端通过不同域名访问,Nginx根据server_name反向代理至对应的应用服务器。
虚拟主机原理基于HTTP请求头中的Host字段是否匹配server_name,感兴趣者可深入研究HTTP协议。
此外,server_name配置还可用于过滤恶意指向该主机服务器的域名。
至此,关于Ubuntu下搭建与配置Nginx服务的介绍已完成,希望对学习有所帮助。