Nginx入门学习笔记

更多精彩教程请访问MacV.com网站!

Nginx 是一款面向性能设计的 HTTP 服务器,能反向代理 HTTP,HTTPS 和邮件相关(SMTP,POP3,IMAP)的协议链接。并且提供了负载均衡以及 HTTP 缓存。它的设计充分使用异步事件模型,削减上下文调度的开销,提高服务器并发能力。采用了模块化设计,提供了丰富模块的第三方模块。

所以关于 Nginx,有这些标签:「异步」「事件」「模块化」「高性能」「高并发」「反向代理」「负载均衡」

Linux系统:Centos 7 x64 Nginx版本:1.11.5

目录

安装

安装依赖

prce(重定向支持)和openssl(https支持,如果不需要https可以不安装。)

1yum install -y pcre-devel 2yum -y install gcc make gcc-c++ wget 3yum -y install openssl openssl-devel

CentOS 6.5 我安装的时候是选择的“基本服务器”,默认这两个包都没安装全,所以这两个都运行安装即可。

下载

nginx的所有版本在这里

1wget http://nginx.org/download/nginx-1.13.3.tar.gz 2wget http://nginx.org/download/nginx-1.13.7.tar.gz 3 4# 如果没有安装wget 5# 下载已编译版本 6$ yum install wget 7 8# 解压压缩包 9tar zxf nginx-1.13.3.tar.gz

编译安装

然后进入目录编译安装,configure参数说明

1cd nginx-1.11.5 2./configure 3 4.... 5Configuration summary 6 + using system PCRE library 7 + OpenSSL library is not used 8 + using system zlib library 9 10 nginx path prefix: "/usr/local/nginx" 11 nginx binary file: "/usr/local/nginx/sbin/nginx" 12 nginx modules path: "/usr/local/nginx/modules" 13 nginx configuration prefix: "/usr/local/nginx/conf" 14 nginx configuration file: "/usr/local/nginx/conf/nginx.conf" 15 nginx pid file: "/usr/local/nginx/logs/nginx.pid" 16 nginx error log file: "/usr/local/nginx/logs/error.log" 17 nginx http access log file: "/usr/local/nginx/logs/access.log" 18 nginx http client request body temporary files: "client_body_temp" 19 nginx http proxy temporary files: "proxy_temp" 20 nginx http fastcgi temporary files: "fastcgi_temp" 21 nginx http uwsgi temporary files: "uwsgi_temp" 22 nginx http scgi temporary files: "scgi_temp"

安装报错误的话比如:“C compiler cc is not found”,这个就是缺少编译环境,安装一下就可以了 yum -y install gcc make gcc-c++ openssl-devel

如果没有error信息,就可以执行下边的安装了:

1make 2make install

nginx测试

运行下面命令会出现两个结果,一般情况nginx会安装在/usr/local/nginx目录中

1cd /usr/local/nginx/sbin/ 2./nginx -t 3 4# nginx: the configuration file /usr/local/nginx/conf/nginx.conf syntax is ok 5# nginx: configuration file /usr/local/nginx/conf/nginx.conf test is successful

设置全局nginx命令

1vi ~/.bash_profile

将下面内容添加到 ~/.bash_profile 文件中

1PATH=$PATH:$HOME/bin:/usr/local/nginx/sbin/ 2export PATH

运行命令 source ~/.bash_profile 让配置立即生效。你就可以全局运行 nginx 命令了。

Mac 安装

Mac OSX 安装特别简单,首先你需要安装 Brew, 通过 brew 快速安装 nginx

安装nginx

1brew install nginx 2# Updating Homebrew... 3# ==> Auto-updated Homebrew! 4# Updated 2 taps (homebrew/core, homebrew/cask). 5# ==> Updated Formulae 6# ==> Installing dependencies for nginx: openssl, pcre 7# ==> Installing nginx dependency: openssl 8# ==> Downloading https://homebrew.bintray.com/bottles/openssl-1.0.2o_1.high_sierra.bottle.tar.gz 9# ######################################################################## 100.0% 10# ==> Pouring openssl-1.0.2o_1.high_sierra.bottle.tar.gz 11# ==> Caveats 12# A CA file has been bootstrapped using certificates from the SystemRoots 13# keychain. To add additional certificates (e.g. the certificates added in 14# the System keychain), place .pem files in 15# /usr/local/etc/openssl/certs 16# 17# and run 18# /usr/local/opt/openssl/bin/c_rehash 19# 20# This formula is keg-only, which means it was not symlinked into /usr/local, 21# because Apple has deprecated use of OpenSSL in favor of its own TLS and crypto libraries. 22# 23# If you need to have this software first in your PATH run: 24# echo 'export PATH="/usr/local/opt/openssl/bin:$PATH"' >> ~/.zshrc 25# 26# For compilers to find this software you may need to set: 27# LDFLAGS: -L/usr/local/opt/openssl/lib 28# CPPFLAGS: -I/usr/local/opt/openssl/include 29# For pkg-config to find this software you may need to set: 30# PKG_CONFIG_PATH: /usr/local/opt/openssl/lib/pkgconfig 31# 32# ==> Summary 33# 🍺 /usr/local/Cellar/openssl/1.0.2o_1: 1,791 files, 12.3MB 34# ==> Installing nginx dependency: pcre 35# ==> Downloading https://homebrew.bintray.com/bottles/pcre-8.42.high_sierra.bottle.tar.gz 36# ######################################################################## 100.0% 37# ==> Pouring pcre-8.42.high_sierra.bottle.tar.gz 38# 🍺 /usr/local/Cellar/pcre/8.42: 204 files, 5.3MB 39# ==> Installing nginx 40# ==> Downloading https://homebrew.bintray.com/bottles/nginx-1.13.12.high_sierra.bottle.tar.gz 41# ######################################################################## 100.0% 42# ==> Pouring nginx-1.13.12.high_sierra.bottle.tar.gz 43# ==> Caveats 44# Docroot is: /usr/local/var/www 45# 46# The default port has been set in /usr/local/etc/nginx/nginx.conf to 8080 so that 47# nginx can run without sudo. 48# 49# nginx will load all files in /usr/local/etc/nginx/servers/. 50# 51# To have launchd start nginx now and restart at login: 52# brew services start nginx 53# Or, if you don't wacd /usr/local/Cellar/nginx/1.13.12/n just run: 54# cd /usr/local/Cellar/nginx/1.13.12/

启动服务

注意默认端口不是 8080 查看确认端口是否被占用。

1brew services start nginx 2# http://localhost:8080/

开机自启动

开机自启动方法一:

编辑 vi /lib/systemd/system/nginx.service 文件,没有创建一个 touch nginx.service 然后将如下内容根据具体情况进行修改后,添加到nginx.service文件中:

1[Unit] 2Description=nginx 3After=network.target remote-fs.target nss-lookup.target 4 5[Service] 6 7Type=forking 8PIDFile=/var/run/nginx.pid 9ExecStartPre=/usr/local/nginx/sbin/nginx -t -c /usr/local/nginx/conf/nginx.conf 10ExecStart=/usr/local/nginx/sbin/nginx -c /usr/local/nginx/conf/nginx.conf 11ExecReload=/bin/kill -s HUP $MAINPID 12ExecStop=/bin/kill -s QUIT $MAINPID 13PrivateTmp=true 14 15[Install] 16WantedBy=multi-user.target
  • [Unit]:服务的说明
  • Description:描述服务
  • After:描述服务类别
  • [Service]服务运行参数的设置
  • Type=forking是后台运行的形式
  • ExecStart为服务的具体运行命令
  • ExecReload为重启命令
  • ExecStop为停止命令
  • PrivateTmp=True表示给服务分配独立的临时空间

注意:[Service]的启动、重启、停止命令全部要求使用绝对路径。

[Install]运行级别下服务安装的相关设置,可设置为多用户,即系统运行级别为3

保存退出。

设置开机启动,使配置生效:

1# 启动nginx服务 2systemctl start nginx.service 3# 停止开机自启动 4systemctl disable nginx.service 5# 查看服务当前状态 6systemctl status nginx.service 7# 查看所有已启动的服务 8systemctl list-units --type=service 9# 重新启动服务 10systemctl restart nginx.service 11# 设置开机自启动 12systemctl enable nginx.service 13# 输出下面内容表示成功了 14Created symlink from /etc/systemd/system/multi-user.target.wants/nginx.service to /usr/lib/systemd/system/nginx.service.
1systemctl is-enabled servicename.service # 查询服务是否开机启动 2systemctl enable *.service # 开机运行服务 3systemctl disable *.service # 取消开机运行 4systemctl start *.service # 启动服务 5systemctl stop *.service # 停止服务 6systemctl restart *.service # 重启服务 7systemctl reload *.service # 重新加载服务配置文件 8systemctl status *.service # 查询服务运行状态 9systemctl --failed # 显示启动失败的服务

注:*代表某个服务的名字,如http的服务名为httpd

开机自启动方法二:

1vi /etc/rc.local 2 3# 在 rc.local 文件中,添加下面这条命令 4/usr/local/nginx/sbin/nginx start

如果开机后发现自启动脚本没有执行,你要去确认一下rc.local这个文件的访问权限是否是可执行的,因为rc.local默认是不可执行的。修改rc.local访问权限,增加可执行权限:

1# /etc/rc.local是/etc/rc.d/rc.local的软连接, 2chmod +x /etc/rc.d/rc.local

官方脚本 ed Hat NGINX Init Script

运维

服务管理

1# 启动 2/usr/local/nginx/sbin/nginx 3 4# 重启 5/usr/local/nginx/sbin/nginx -s reload 6 7# 关闭进程 8/usr/local/nginx/sbin/nginx -s stop 9 10# 平滑关闭nginx 11/usr/local/nginx/sbin/nginx -s quit 12 13# 查看nginx的安装状态, 14/usr/local/nginx/sbin/nginx -V

关闭防火墙,或者添加防火墙规则就可以测试了

1service iptables stop

或者编辑配置文件:

1vi /etc/sysconfig/iptables

添加这样一条开放80端口的规则后保存:

1-A INPUT -m state --state NEW -m tcp -p tcp --dport 80 -j ACCEPT

重启服务即可:

1service iptables restart 2# 命令进行查看目前nat 3iptables -t nat -L

重启服务防火墙报错解决

1service iptables restart 2# Redirecting to /bin/systemctl restart iptables.service 3# Failed to restart iptables.service: Unit iptables.service failed to load: No such file or directory.

在CentOS 7或RHEL 7或Fedora中防火墙由 firewalld 来管理,当然你可以还原传统的管理方式。或则使用新的命令进行管理。 假如采用传统请执行一下命令:

1# 传统命令 2systemctl stop firewalld 3systemctl mask firewalld
1# 安装命令 2yum install iptables-services 3 4systemctl enable iptables 5service iptables restart

nginx卸载

如果通过yum安装,使用下面命令安装。

1yum remove nginx

编译安装,删除/usr/local/nginx目录即可 如果配置了自启动脚本,也需要删除。

参数说明

参数说明
--prefix=<path>Nginx安装路径。如果没有指定,默认为 /usr/local/nginx。
--sbin-path=<path>Nginx可执行文件安装路径。只能安装时指定,如果没有指定,默认为<prefix>/sbin/nginx。
--conf-path=<path>在没有给定-c选项下默认的nginx.conf的路径。如果没有指定,默认为<prefix>/conf/nginx.conf。
--pid-path=<path>在nginx.conf中没有指定pid指令的情况下,默认的nginx.pid的路径。如果没有指定,默认为 <prefix>/logs/nginx.pid。
--lock-path=<path>nginx.lock文件的路径。
--error-log-path=<path>在nginx.conf中没有指定error_log指令的情况下,默认的错误日志的路径。如果没有指定,默认为 <prefix>/- logs/error.log。
--http-log-path=<path>在nginx.conf中没有指定access_log指令的情况下,默认的访问日志的路径。如果没有指定,默认为 <prefix>/- logs/access.log。
--user=<user>在nginx.conf中没有指定user指令的情况下,默认的nginx使用的用户。如果没有指定,默认为 nobody。
--group=<group>在nginx.conf中没有指定user指令的情况下,默认的nginx使用的组。如果没有指定,默认为 nobody。
--builddir=DIR指定编译的目录
--with-rtsig_module启用 rtsig 模块
--with-select_module --without-select_module允许或不允许开启SELECT模式,如果 configure 没有找到更合适的模式,比如:kqueue(sun os),epoll (linux kenel 2.6+), rtsig(- 实时信号)或者/dev/poll(一种类似select的模式,底层实现与SELECT基本相 同,都是采用轮训方法) SELECT模式将是默认安装模式
--with-poll_module --without-poll_moduleWhether or not to enable the poll module. This module is enabled by, default if a more suitable method such as kqueue, epoll, rtsig or /dev/poll is not discovered by configure.
--with-http_ssl_moduleEnable ngx_http_ssl_module. Enables SSL support and the ability to handle HTTPS requests. Requires OpenSSL. On Debian, this is libssl-dev. 开启HTTP SSL模块,使NGINX可以支持HTTPS请求。这个模块需要已经安装了OPENSSL,在DEBIAN上是libssl
--with-http_realip_module启用 ngx_http_realip_module
--with-http_addition_module启用 ngx_http_addition_module
--with-http_sub_module启用 ngx_http_sub_module
--with-http_dav_module启用 ngx_http_dav_module
--with-http_flv_module启用 ngx_http_flv_module
--with-http_stub_status_module启用 "server status" 页
--without-http_charset_module禁用 ngx_http_charset_module
--without-http_gzip_module禁用 ngx_http_gzip_module. 如果启用,需要 zlib 。
--without-http_ssi_module禁用 ngx_http_ssi_module
--without-http_userid_module禁用 ngx_http_userid_module
--without-http_access_module禁用 ngx_http_access_module
--without-http_auth_basic_module禁用 ngx_http_auth_basic_module
--without-http_autoindex_module禁用 ngx_http_autoindex_module
--without-http_geo_module禁用 ngx_http_geo_module
--without-http_map_module禁用 ngx_http_map_module
--without-http_referer_module禁用 ngx_http_referer_module
--without-http_rewrite_module禁用 ngx_http_rewrite_module. 如果启用需要 PCRE 。
--without-http_proxy_module禁用 ngx_http_proxy_module
--without-http_fastcgi_module禁用 ngx_http_fastcgi_module
--without-http_memcached_module禁用 ngx_http_memcached_module
--without-http_limit_zone_module禁用 ngx_http_limit_zone_module
--without-http_empty_gif_module禁用 ngx_http_empty_gif_module
--without-http_browser_module禁用 ngx_http_browser_module
--without-http_upstream_ip_hash_module禁用 ngx_http_upstream_ip_hash_module
--with-http_perl_module启用 ngx_http_perl_module
--with-perl_modules_path=PATH指定 perl 模块的路径
--with-perl=PATH指定 perl 执行文件的路径
--http-log-path=PATHSet path to the http access log
--http-client-body-temp-path=PATHSet path to the http client request body temporary files
--http-proxy-temp-path=PATHSet path to the http proxy temporary files
--http-fastcgi-temp-path=PATHSet path to the http fastcgi temporary files
--without-http禁用 HTTP server
--with-mail启用 IMAP4/POP3/SMTP 代理模块
--with-mail_ssl_module启用 ngx_mail_ssl_module
--with-cc=PATH指定 C 编译器的路径
--with-cpp=PATH指定 C 预处理器的路径
--with-cc-opt=OPTIONSAdditional parameters which will be added to the variable CFLAGS. With the use of the system library PCRE in FreeBSD, it is necessary to indicate --with-cc-opt="-I /usr/local/include". If we are using select() and it is necessary to increase the number of file descriptors, then this also can be assigned here: --with-cc-opt="-D FD_SETSIZE=2048".
--with-ld-opt=OPTIONSAdditional parameters passed to the linker. With the use of the system library PCRE in - FreeBSD, it is necessary to indicate --with-ld-opt="-L /usr/local/lib".
--with-cpu-opt=CPU为特定的 CPU 编译,有效的值包括:pentium, pentiumpro, pentium3, pentium4, athlon, opteron, amd64, sparc32, sparc64, ppc64
--without-pcre禁止 PCRE 库的使用。同时也会禁止 HTTP rewrite 模块。在 "location" 配置指令中的正则表达式也需要 PCRE 。
--with-pcre=DIR指定 PCRE 库的源代码的路径。
--with-pcre-opt=OPTIONSSet additional options for PCRE building.
--with-md5=DIRSet path to md5 library sources.
--with-md5-opt=OPTIONSSet additional options for md5 building.
--with-md5-asmUse md5 assembler sources.
--with-sha1=DIRSet path to sha1 library sources.
--with-sha1-opt=OPTIONSSet additional options for sha1 building.
--with-sha1-asmUse sha1 assembler sources.
--with-zlib=DIRSet path to zlib library sources.
--with-zlib-opt=OPTIONSSet additional options for zlib building.
--with-zlib-asm=CPUUse zlib assembler sources optimized for specified CPU, valid values are: pentium, pentiumpro
--with-openssl=DIRSet path to OpenSSL library sources
--with-openssl-opt=OPTIONSSet additional options for OpenSSL building
--with-debug启用调试日志
--add-module=PATHAdd in a third-party module found in directory PATH

配置

在Centos 默认配置文件在 /usr/local/nginx-1.5.1/conf/nginx.conf 我们要在这里配置一些文件。nginx.conf是主配置文件,由若干个部分组成,每个大括号{}表示一个部分。每一行指令都由分号结束;,标志着一行的结束。

常用正则

正则说明正则说明
. 匹配除换行符以外的任意字符$ 匹配字符串的结束
? 重复0次或1次{n} 重复n次
+ 重复1次或更多次{n,} 重复n次或更多次
*重复0次或更多次[c] 匹配单个字符c
\d 匹配数字[a-z]匹配a-z小写字母的任意一个
^ 匹配字符串的开始--

全局变量

变量说明变量说明
$args这个变量等于请求行中的参数,同$query_string$remote_port客户端的端口。
$content_length请求头中的Content-length字段。$remote_user已经经过Auth Basic Module验证的用户名。
$content_type请求头中的Content-Type字段。$request_filename当前请求的文件路径,由root或alias指令与URI请求生成。
$document_root当前请求在root指令中指定的值。$schemeHTTP方法(如http,https)。
$host请求主机头字段,否则为服务器名称。$server_protocol请求使用的协议,通常是HTTP/1.0或HTTP/1.1。
$http_user_agent客户端agent信息$server_addr服务器地址,在完成一次系统调用后可以确定这个值。
$http_cookie客户端cookie信息$server_name服务器名称。
$limit_rate这个变量可以限制连接速率。$server_port请求到达服务器的端口号。
$request_method客户端请求的动作,通常为GET或POST。$request_uri包含请求参数的原始URI,不包含主机名,如:/foo/bar.php?arg=baz。
$remote_addr客户端的IP地址。$uri不带请求参数的当前URI,$uri不包含主机名,如/foo/bar.html。
$document_uri与$uri相同。--

例如请求:http://localhost:3000/test1/test2/test.php

$host:localhost
$server_port:3000
$request_uri:/test1/test2/test.php
$document_uri:/test1/test2/test.php
$document_root:/var/www/html
$request_filename:/var/www/html/test1/test2/test.php

符号参考

符号说明符号说明符号说明
k,K千字节m,M兆字节ms毫秒
sm分钟h小时
dwM一个月, 30天

例如,"8k","1m" 代表字节数计量。
例如,"1h 30m","1y 6M"。代表 "1小时 30分","1年零6个月"。

配置文件

nginx 的配置系统由一个主配置文件和其他一些辅助的配置文件构成。这些配置文件均是纯文本文件,全部位于 nginx 安装目录下的 conf 目录下。

指令由 nginx 的各个模块提供,不同的模块会提供不同的指令来实现配置。 指令除了 Key-Value 的形式,还有作用域指令。

nginx.conf 中的配置信息,根据其逻辑上的意义,对它们进行了分类,也就是分成了多个作用域,或者称之为配置指令上下文。不同的作用域含有一个或者多个配置项。

下面的这些上下文指令是用的比较多:

DirectiveDescriptionContains Directive
mainnginx 在运行时与具体业务功能(比如 http 服务或者 email 服务代理)无关的一些参数,比如工作进程数,运行的身份等。user, worker_processes, error_log, events, http, mail
http与提供 http 服务相关的一些配置参数。例如:是否使用 keepalive 啊,是否使用 gzip 进行压缩等。server
serverhttp 服务上支持若干虚拟主机。每个虚拟主机一个对应的 server 配置项,配置项里面包含该虚拟主机相关的配置。在提供 mail 服务的代理时,也可以建立若干 server. 每个 server 通过监听的地址来区分。listen, server_name, access_log, location, protocol, proxy, smtp_auth, xclient
locationhttp 服务中,某些特定的 URL 对应的一系列配置项。index, root
mail实现 email 相关的 SMTP/IMAP/POP3 代理时,共享的一些配置项(因为可能实现多个代理,工作在多个监听地址上)。server, http, imap_capabilities
include以便增强配置文件的可读性,使得部分配置文件可以重新使用。-
valid_referers用来校验Http请求头Referer是否有效。-
try_files用在server部分,不过最常见的还是用在location部分,它会按照给定的参数顺序进行尝试,第一个被匹配到的将会被使用。-
if当在location块中使用if指令,在某些情况下它并不按照预期运行,一般来说避免使用if指令。-

例如我们再 nginx.conf 里面引用两个配置 vhost/example.com.conf 和 vhost/gitlab.com.conf 它们都被放在一个我自己新建的目录 vhost 下面。nginx.conf 配置如下:

1worker_processes 1; 2events { 3 worker_connections 1024; 4} 5 6http { 7 include mime.types; 8 default_type application/octet-stream; 9 10 #log_format main '$remote_addr - $remote_user [$time_local] "$request" ' 11 # '$status $body_bytes_sent "$http_referer" ' 12 # '"$http_user_agent" "$http_x_forwarded_for"'; 13 14 #access_log logs/access.log main; 15 16 sendfile on; 17 #tcp_nopush on; 18 19 #keepalive_timeout 0; 20 keepalive_timeout 65; 21 22 #gzip on; 23 server { 24 listen 80; 25 server_name localhost; 26 location / { 27 root html; 28 index index.html index.htm; 29 } 30 error_page 500 502 503 504 /50x.html; 31 location = /50x.html { 32 root html; 33 } 34 } 35 include vhost/example.com.conf; 36 include vhost/gitlab.com.conf; 37}

简单的配置: example.com.conf

1server { 2 #侦听的80端口 3 listen 80; 4 server_name baidu.com app.baidu.com; # 这里指定域名 5 index index.html index.htm; # 这里指定默认入口页面 6 root /home/www/app.baidu.com; # 这里指定目录 7}

内置预定义变量

Nginx提供了许多预定义的变量,也可以通过使用set来设置变量。你可以在if中使用预定义变量,也可以将它们传递给代理服务器。以下是一些常见的预定义变量,更多详见

变量名称
$args_name在请求中的name参数
$args所有请求参数
$query_string$args的别名
$content_length请求头Content-Length的值
$content_type请求头Content-Type的值
$host如果当前有Host,则为请求头Host的值;如果没有这个头,那么该值等于匹配该请求的server_name的值
$remote_addr客户端的IP地址
$request完整的请求,从客户端收到,包括Http请求方法、URI、Http协议、头、请求体
$request_uri完整请求的URI,从客户端来的请求,包括参数
$scheme当前请求的协议
$uri当前请求的标准化URI

反向代理

反向代理是一个Web服务器,它接受客户端的连接请求,然后将请求转发给上游服务器,并将从服务器得到的结果返回给连接的客户端。下面简单的反向代理的例子:

1server { 2 listen 80; 3 server_name localhost; 4 client_max_body_size 1024M; # 允许客户端请求的最大单文件字节数 5 6 location / { 7 proxy_pass http://localhost:8080; 8 proxy_set_header Host $host:$server_port; 9 proxy_set_header X-Forwarded-For $remote_addr; # HTTP的请求端真实的IP 10 proxy_set_header X-Forwarded-Proto $scheme; # 为了正确地识别实际用户发出的协议是 http 还是 https 11 } 12}

复杂的配置: gitlab.com.conf。

1server { 2 #侦听的80端口 3 listen 80; 4 server_name git.example.cn; 5 location / { 6 proxy_pass http://localhost:3000; 7 #以下是一些反向代理的配置可删除 8 proxy_redirect off; 9 #后端的Web服务器可以通过X-Forwarded-For获取用户真实IP 10 proxy_set_header Host $host; 11 client_max_body_size 10m; #允许客户端请求的最大单文件字节数 12 client_body_buffer_size 128k; #缓冲区代理缓冲用户端请求的最大字节数 13 proxy_connect_timeout 300; #nginx跟后端服务器连接超时时间(代理连接超时) 14 proxy_send_timeout 300; #后端服务器数据回传时间(代理发送超时) 15 proxy_read_timeout 300; #连接成功后,后端服务器响应时间(代理接收超时) 16 proxy_buffer_size 4k; #设置代理服务器(nginx)保存用户头信息的缓冲区大小 17 proxy_buffers 4 32k; #proxy_buffers缓冲区,网页平均在32k以下的话,这样设置 18 proxy_busy_buffers_size 64k; #高负荷下缓冲大小(proxy_buffers*2) 19 } 20}

代理到上游服务器的配置中,最重要的是proxy_pass指令。以下是代理模块中的一些常用指令:

指令说明
proxy_connect_timeoutNginx从接受请求至连接到上游服务器的最长等待时间
proxy_send_timeout后端服务器数据回传时间(代理发送超时)
proxy_read_timeout连接成功后,后端服务器响应时间(代理接收超时)
proxy_cookie_domain替代从上游服务器来的Set-Cookie头的domain属性
proxy_cookie_path替代从上游服务器来的Set-Cookie头的path属性
proxy_buffer_size设置代理服务器(nginx)保存用户头信息的缓冲区大小
proxy_buffersproxy_buffers缓冲区,网页平均在多少k以下
proxy_set_header重写发送到上游服务器头的内容,也可以通过将某个头部的值设置为空字符串,而不发送某个头部的方法实现
proxy_ignore_headers这个指令禁止处理来自代理服务器的应答。
proxy_intercept_errors使nginx阻止HTTP应答代码为400或者更高的应答。

负载均衡

upstream指令启用一个新的配置区段,在该区段定义一组上游服务器。这些服务器可能被设置不同的权重,也可能出于对服务器进行维护,标记为down。

1upstream gitlab { 2 ip_hash; 3 # upstream的负载均衡,weight是权重,可以根据机器配置定义权重。weigth参数表示权值,权值越高被分配到的几率越大。 4 server 192.168.122.11:8081 ; 5 server 127.0.0.1:82 weight=3; 6 server 127.0.0.1:83 weight=3 down; 7 server 127.0.0.1:84 weight=3; max_fails=3 fail_timeout=20s; 8 server 127.0.0.1:85 weight=4;; 9 keepalive 32; 10} 11server { 12 #侦听的80端口 13 listen 80; 14 server_name git.example.cn; 15 location / { 16 proxy_pass http://gitlab; #在这里设置一个代理,和upstream的名字一样 17 #以下是一些反向代理的配置可删除 18 proxy_redirect off; 19 #后端的Web服务器可以通过X-Forwarded-For获取用户真实IP 20 proxy_set_header Host $host; 21 proxy_set_header X-Real-IP $remote_addr; 22 proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; 23 client_max_body_size 10m; #允许客户端请求的最大单文件字节数 24 client_body_buffer_size 128k; #缓冲区代理缓冲用户端请求的最大字节数 25 proxy_connect_timeout 300; #nginx跟后端服务器连接超时时间(代理连接超时) 26 proxy_send_timeout 300; #后端服务器数据回传时间(代理发送超时) 27 proxy_read_timeout 300; #连接成功后,后端服务器响应时间(代理接收超时) 28 proxy_buffer_size 4k; #设置代理服务器(nginx)保存用户头信息的缓冲区大小 29 proxy_buffers 4 32k;# 缓冲区,网页平均在32k以下的话,这样设置 30 proxy_busy_buffers_size 64k; #高负荷下缓冲大小(proxy_buffers*2) 31 proxy_temp_file_write_size 64k; #设定缓存文件夹大小,大于这个值,将从upstream服务器传 32 } 33}

每个请求按时间顺序逐一分配到不同的后端服务器,如果后端服务器down掉,能自动剔除。

负载均衡:

upstream模块能够使用3种负载均衡算法:轮询、IP哈希、最少连接数。

轮询: 默认情况下使用轮询算法,不需要配置指令来激活它,它是基于在队列中谁是下一个的原理确保访问均匀地分布到每个上游服务器;
IP哈希: 通过ip_hash指令来激活,Nginx通过IPv4地址的前3个字节或者整个IPv6地址作为哈希键来实现,同一个IP地址总是能被映射到同一个上游服务器;
最少连接数: 通过least_conn指令来激活,该算法通过选择一个活跃数最少的上游服务器进行连接。如果上游服务器处理能力不同,可以通过给server配置weight权重来说明,该算法将考虑到不同服务器的加权最少连接数。

RR

简单配置 ,这里我配置了2台服务器,当然实际上是一台,只是端口不一样而已,而8081的服务器是不存在的,也就是说访问不到,但是我们访问 http://localhost 的时候,也不会有问题,会默认跳转到http://localhost:8080具体是因为Nginx会自动判断服务器的状态,如果服务器处于不能访问(服务器挂了),就不会跳转到这台服务器,所以也避免了一台服务器挂了影响使用的情况,由于Nginx默认是RR策略,所以我们不需要其他更多的设置

1upstream test { 2 server localhost:8080; 3 server localhost:8081; 4} 5server { 6 listen 81; 7 server_name localhost; 8 client_max_body_size 1024M; 9 10 location / { 11 proxy_pass http://test; 12 proxy_set_header Host $host:$server_port; 13 } 14}

负载均衡的核心代码为

1upstream test { 2 server localhost:8080; 3 server localhost:8081; 4}

权重

指定轮询几率,weight和访问比率成正比,用于后端服务器性能不均的情况。 例如

1upstream test { 2 server localhost:8080 weight=9; 3 server localhost:8081 weight=1; 4}

那么10次一般只会有1次会访问到8081,而有9次会访问到8080

ip_hash

上面的2种方式都有一个问题,那就是下一个请求来的时候请求可能分发到另外一个服务器,当我们的程序不是无状态的时候(采用了session保存数据),这时候就有一个很大的很问题了,比如把登录信息保存到了session中,那么跳转到另外一台服务器的时候就需要重新登录了,所以很多时候我们需要一个客户只访问一个服务器,那么就需要用iphash了,iphash的每个请求按访问ip的hash结果分配,这样每个访客固定访问一个后端服务器,可以解决session的问题。

1upstream test { 2 ip_hash; 3 server localhost:8080; 4 server localhost:8081; 5}

fair

这是个第三方模块,按后端服务器的响应时间来分配请求,响应时间短的优先分配。

1upstream backend { 2 fair; 3 server localhost:8080; 4 server localhost:8081; 5}

url_hash

这是个第三方模块,按访问url的hash结果来分配请求,使每个url定向到同一个后端服务器,后端服务器为缓存时比较有效。 在upstream中加入hash语句,server语句中不能写入weight等其他的参数,hash_method是使用的hash算法

1upstream backend { 2 hash $request_uri; 3 hash_method crc32; 4 server localhost:8080; 5 server localhost:8081; 6}

以上5种负载均衡各自适用不同情况下使用,所以可以根据实际情况选择使用哪种策略模式,不过fair和url_hash需要安装第三方模块才能使用

server指令可选参数:

  1. weight:设置一个服务器的访问权重,数值越高,收到的请求也越多;
  2. fail_timeout:在这个指定的时间内服务器必须提供响应,如果在这个时间内没有收到响应,那么服务器将会被标记为down状态;
  3. max_fails:设置在fail_timeout时间之内尝试对一个服务器连接的最大次数,如果超过这个次数,那么服务器将会被标记为down;
  4. down:标记一个服务器不再接受任何请求;
  5. backup:一旦其他服务器宕机,那么有该标记的机器将会接收请求。

keepalive指令:

Nginx服务器将会为每一个worker进行保持同上游服务器的连接。

屏蔽ip

在nginx的配置文件nginx.conf中加入如下配置,可以放到http, server, location, limit_except语句块,需要注意相对路径,本例当中nginx.confblocksip.conf在同一个目录中。

1include blockip.conf;

在blockip.conf里面输入内容,如:

1deny 165.91.122.67; 2 3deny IP; # 屏蔽单个ip访问 4allow IP; # 允许单个ip访问 5deny all; # 屏蔽所有ip访问 6allow all; # 允许所有ip访问 7deny 123.0.0.0/8 # 屏蔽整个段即从123.0.0.1到123.255.255.254访问的命令 8deny 124.45.0.0/16 # 屏蔽IP段即从123.45.0.1到123.45.255.254访问的命令 9deny 123.45.6.0/24 # 屏蔽IP段即从123.45.6.1到123.45.6.254访问的命令 10 11# 如果你想实现这样的应用,除了几个IP外,其他全部拒绝 12allow 1.1.1.1; 13allow 1.1.1.2; 14deny all;

第三方模块安装方法

./configure --prefix=/你的安装目录  --add-module=/第三方模块目录

重定向

  • permanent 永久性重定向。请求日志中的状态码为301
  • redirect 临时重定向。请求日志中的状态码为302

重定向整个网站

1server { 2 server_name old-site.com 3 return 301 $scheme://new-site.com$request_uri; 4}

重定向单页

1server { 2 location = /oldpage.html { 3 return 301 http://example.org/newpage.html; 4 } 5}

重定向整个子路径

1location /old-site { 2 rewrite ^/old-site/(.*) http://example.org/new-site/$1 permanent; 3}

性能

内容缓存

允许浏览器基本上永久地缓存静态内容。 Nginx将为您设置Expires和Cache-Control头信息。

1location /static { 2 root /data; 3 expires max; 4}

如果要求浏览器永远不会缓存响应(例如用于跟踪请求),请使用-1。

1location = /empty.gif { 2 empty_gif; 3 expires -1; 4}

Gzip压缩

1gzip on; 2gzip_buffers 16 8k; 3gzip_comp_level 6; 4gzip_http_version 1.1; 5gzip_min_length 256; 6gzip_proxied any; 7gzip_vary on; 8gzip_types 9 text/xml application/xml application/atom+xml application/rss+xml application/xhtml+xml image/svg+xml 10 text/javascript application/javascript application/x-javascript 11 text/x-json application/json application/x-web-app-manifest+json 12 text/css text/plain text/x-component 13 font/opentype application/x-font-ttf application/vnd.ms-fontobject 14 image/x-icon; 15gzip_disable "msie6";

打开文件缓存

1open_file_cache max=1000 inactive=20s; 2open_file_cache_valid 30s; 3open_file_cache_min_uses 2; 4open_file_cache_errors on;

SSL缓存

1ssl_session_cache shared:SSL:10m; 2ssl_session_timeout 10m;

上游Keepalive

1upstream backend { 2 server 127.0.0.1:8080; 3 keepalive 32; 4} 5server { 6 ... 7 location /api/ { 8 proxy_pass http://backend; 9 proxy_http_version 1.1; 10 proxy_set_header Connection ""; 11 } 12}

监控

使用ngxtop实时解析nginx访问日志,并且将处理结果输出到终端,功能类似于系统命令top。所有示例都读取nginx配置文件的访问日志位置和格式。如果要指定访问日志文件和/或日志格式,请使用-f和-a选项。

注意:在nginx配置中/usr/local/nginx/conf/nginx.conf日志文件必须是绝对路径。

1# 安装 ngxtop 2pip install ngxtop 3 4# 实时状态 5ngxtop 6# 状态为404的前10个请求的路径: 7ngxtop top request_path --filter 'status == 404' 8 9# 发送总字节数最多的前10个请求 10ngxtop --order-by 'avg(bytes_sent) * count' 11 12# 排名前十位的IP,例如,谁攻击你最多 13ngxtop --group-by remote_addr 14 15# 打印具有4xx或5xx状态的请求,以及status和http referer 16ngxtop -i 'status >= 400' print request status http_referer 17 18# 由200个请求路径响应发送的平均正文字节以'foo'开始: 19ngxtop avg bytes_sent --filter 'status == 200 and request_path.startswith("foo")' 20 21# 使用“common”日志格式从远程机器分析apache访问日志 22ssh remote tail -f /var/log/apache2/access.log | ngxtop -f common

常见使用场景

跨域问题

在工作中,有时候会遇到一些接口不支持跨域,这时候可以简单的添加add_headers来支持cors跨域。配置如下:

1server { 2 listen 80; 3 server_name api.xxx.com; 4 5 add_header 'Access-Control-Allow-Origin' '*'; 6 add_header 'Access-Control-Allow-Credentials' 'true'; 7 add_header 'Access-Control-Allow-Methods' 'GET,POST,HEAD'; 8 9 location / { 10 proxy_pass http://127.0.0.1:3000; 11 proxy_set_header X-Real-IP $remote_addr; 12 proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; 13 proxy_set_header Host $http_host; 14 } 15}

上面更改头信息,还有一种,使用 rewrite 指令重定向URI来解决跨域问题。

1upstream test { 2 server 127.0.0.1:8080; 3 server localhost:8081; 4} 5server { 6 listen 80; 7 server_name api.xxx.com; 8 location / { 9 root html; #去请求../html文件夹里的文件 10 index index.html index.htm; #首页响应地址 11 } 12 # 用于拦截请求,匹配任何以 /api/开头的地址, 13 # 匹配符合以后,停止往下搜索正则。 14 location ^~/api/{ 15 # 代表重写拦截进来的请求,并且只能对域名后边的除去传递的参数外的字符串起作用, 16 # 例如www.a.com/proxy/api/msg?meth=1&par=2重写,只对/proxy/api/msg重写。 17 # rewrite后面的参数是一个简单的正则 ^/api/(.*)$, 18 # $1代表正则中的第一个(),$2代表第二个()的值,以此类推。 19 rewrite ^/api/(.*)$ /$1 break; 20 21 # 把请求代理到其他主机 22 # 其中 http://www.b.com/ 写法和 http://www.b.com写法的区别如下 23 # 如果你的请求地址是他 http://server/html/test.jsp 24 # 配置一: http://www.b.com/ 后面有“/” 25 # 将反向代理成 http://www.b.com/html/test.jsp 访问 26 # 配置一: http://www.b.com 后面没有有“/” 27 # 将反向代理成 http://www.b.com/test.jsp 访问 28 proxy_pass http://test; 29 30 # 如果 proxy_pass URL 是 http://a.xx.com/platform/ 这种情况 31 # proxy_cookie_path应该设置成 /platform/ / (注意两个斜杠之间有空格)。 32 proxy_cookie_path /platfrom/ /; 33 34 # http://nginx.org/en/docs/http/ngx_http_proxy_module.html#proxy_pass_header 35 # 设置 Cookie 头通过 36 proxy_pass_header Set-Cookie; 37 } 38}

跳转到带www的域上面

1server { 2 listen 80; 3 # 配置正常的带www的域名 4 server_name www.wangchujiang.com; 5 root /home/www/wabg/download; 6 location / { 7 try_files $uri $uri/ /index.html =404; 8 } 9} 10server { 11 # 这个要放到下面, 12 # 将不带www的 wangchujiang.com 永久性重定向到 https://www.wangchujiang.com 13 server_name wangchujiang.com; 14 rewrite ^(.*) https://www.wangchujiang.com$1 permanent; 15}

代理转发

1upstream server-api{ 2 # api 代理服务地址 3 server 127.0.0.1:3110; 4} 5upstream server-resource{ 6 # 静态资源 代理服务地址 7 server 127.0.0.1:3120; 8} 9server { 10 listen 3111; 11 server_name localhost; # 这里指定域名 12 root /home/www/server-statics; 13 # 匹配 api 路由的反向代理到API服务 14 location ^~/api/ { 15 rewrite ^/(.*)$ /$1 break; 16 proxy_pass http://server-api; 17 } 18 # 假设这里验证码也在API服务中 19 location ^~/captcha { 20 rewrite ^/(.*)$ /$1 break; 21 proxy_pass http://server-api; 22 } 23 # 假设你的图片资源全部在另外一个服务上面 24 location ^~/img/ { 25 rewrite ^/(.*)$ /$1 break; 26 proxy_pass http://server-resource; 27 } 28 # 路由在前端,后端没有真实路由,在路由不存在的 404状态的页面返回 /index.html 29 # 这个方式使用场景,你在写React或者Vue项目的时候,没有真实路由 30 location / { 31 try_files $uri $uri/ /index.html =404; 32        #                               ^ 空格很重要 33    } 34}

监控状态信息

通过 nginx -V 来查看是否有 with-http_stub_status_module 该模块。

nginx -V 这里 V 是大写的,如果是小写的 vnginx -v,则不会出现有哪些模块,只会出现 nginx 的版本

1location /nginx_status { 2 stub_status on; 3 access_log off; 4}

通过 http://127.0.0.1/nginx_status 访问出现下面结果。

1Active connections: 3 2server accepts handled requests 3 7 7 5 4Reading: 0 Writing: 1 Waiting: 2
  1. 主动连接(第 1 行)

当前与http建立的连接数,包括等待的客户端连接:3

  1. 服务器接受处理的请求(第 2~3 行)

接受的客户端连接总数目:7
处理的客户端连接总数目:7
客户端总的请求数目:5

  1. 读取其它信(第 4 行)

当前,nginx读请求连接
当前,nginx写响应返回给客户端
目前有多少空闲客户端请求连接

代理转发连接替换

1location ^~/api/upload { 2 rewrite ^/(.*)$ /wfs/v1/upload break; 3 proxy_pass http://wfs-api; 4}

ssl配置

超文本传输安全协议(缩写:HTTPS,英语:Hypertext Transfer Protocol Secure)是超文本传输协议和SSL/TLS的组合,用以提供加密通讯及对网络服务器身份的鉴定。HTTPS连接经常被用于万维网上的交易支付和企业信息系统中敏感信息的传输。HTTPS不应与在RFC 2660中定义的安全超文本传输协议(S-HTTP)相混。HTTPS 目前已经是所有注重隐私和安全的网站的首选,随着技术的不断发展,HTTPS 网站已不再是大型网站的专利,所有普通的个人站长和博客均可以自己动手搭建一个安全的加密的网站。

创建SSL证书,如果你购买的证书,就可以直接下载

1sudo mkdir /etc/nginx/ssl 2# 创建了有效期100年,加密强度为RSA2048的SSL密钥key和X509证书文件。 3sudo openssl req -x509 -nodes -days 36500 -newkey rsa:2048 -keyout /etc/nginx/ssl/nginx.key -out /etc/nginx/ssl/nginx.crt 4# 上面命令,会有下面需要填写内容 5Country Name (2 letter code) [AU]:US 6State or Province Name (full name) [Some-State]:New York 7Locality Name (eg, city) []:New York City 8Organization Name (eg, company) [Internet Widgits Pty Ltd]:Bouncy Castles, Inc. 9Organizational Unit Name (eg, section) []:Ministry of Water Slides 10Common Name (e.g. server FQDN or YOUR name) []:your_domain.com 11Email Address []:admin@your_domain.com

创建自签证书

1首先,创建证书和私钥的目录 2# mkdir -p /etc/nginx/cert 3# cd /etc/nginx/cert 4创建服务器私钥,命令会让你输入一个口令: 5# openssl genrsa -des3 -out nginx.key 2048 6创建签名请求的证书(CSR): 7# openssl req -new -key nginx.key -out nginx.csr 8在加载SSL支持的Nginx并使用上述私钥时除去必须的口令: 9# cp nginx.key nginx.key.org 10# openssl rsa -in nginx.key.org -out nginx.key 11最后标记证书使用上述私钥和CSR: 12# openssl x509 -req -days 365 -in nginx.csr -signkey nginx.key -out nginx.crt

查看目前nginx编译选项

sbin/nginx -V

输出下面内容

1nginx version: nginx/1.7.8 2built by gcc 4.4.7 20120313 (Red Hat 4.4.7-4) (GCC) 3TLS SNI support enabled 4configure arguments: --prefix=/usr/local/nginx-1.7.8 --with-http_ssl_module --with-http_spdy_module --with-http_stub_status_module --with-pcre

如果依赖的模块不存在,可以进入安装目录,输入下面命令重新编译安装。

1./configure --prefix=/usr/local/nginx --with-http_stub_status_module --with-http_ssl_module

运行完成之后还需要make (不用make install)

1# 备份nginx的二进制文件 2cp -rf /usr/local/nginx/sbin/nginx  /usr/local/nginx/sbin/nginx.bak 3# 覆盖nginx的二进制文件 4cp -rf objs/nginx /usr/local/nginx/sbin/

HTTPS server

1server { 2 listen 443 ssl; 3 server_name localhost; 4 5 ssl_certificate /etc/nginx/ssl/nginx.crt; 6 ssl_certificate_key /etc/nginx/ssl/nginx.key; 7 # 禁止在header中出现服务器版本,防止黑客利用版本漏洞攻击 8 server_tokens off; 9 # 设置ssl/tls会话缓存的类型和大小。如果设置了这个参数一般是shared,buildin可能会参数内存碎片,默认是none,和off差不多,停用缓存。如shared:SSL:10m表示我所有的nginx工作进程共享ssl会话缓存,官网介绍说1M可以存放约4000个sessions。 10 ssl_session_cache shared:SSL:1m; 11 12 # 客户端可以重用会话缓存中ssl参数的过期时间,内网系统默认5分钟太短了,可以设成30m即30分钟甚至4h。 13 ssl_session_timeout 5m; 14 15 # 选择加密套件,不同的浏览器所支持的套件(和顺序)可能会不同。 16 # 这里指定的是OpenSSL库能够识别的写法,你可以通过 openssl -v cipher 'RC4:HIGH:!aNULL:!MD5'(后面是你所指定的套件加密算法) 来看所支持算法。 17 ssl_ciphers HIGH:!aNULL:!MD5; 18 19 # 设置协商加密算法时,优先使用我们服务端的加密套件,而不是客户端浏览器的加密套件。 20 ssl_prefer_server_ciphers on; 21 22 location / { 23 root html; 24 index index.html index.htm; 25 } 26}

强制将http重定向到https

1server { 2 listen 80; 3 server_name example.com; 4 rewrite ^ https://$http_host$request_uri? permanent; # 强制将http重定向到https 5 # 在错误页面和“服务器”响应头字段中启用或禁用发射nginx版本。 防止黑客利用版本漏洞攻击 6 server_tokens off; 7}

两个虚拟主机

纯静态-html 支持

1http { 2 server { 3 listen 80; 4 server_name www.domain1.com; 5 access_log logs/domain1.access.log main; 6 location / { 7 index index.html; 8 root /var/www/domain1.com/htdocs; 9 } 10 } 11 server { 12 listen 80; 13 server_name www.domain2.com; 14 access_log logs/domain2.access.log main; 15 location / { 16 index index.html; 17 root /var/www/domain2.com/htdocs; 18 } 19 } 20}

虚拟主机标准配置

1http { 2 server { 3 listen 80 default; 4 server_name _ *; 5 access_log logs/default.access.log main; 6 location / { 7 index index.html; 8 root /var/www/default/htdocs; 9 } 10 } 11}

爬虫过滤

根据 User-Agent 过滤请求,通过一个简单的正则表达式,就可以过滤不符合要求的爬虫请求(初级爬虫)。

~* 表示不区分大小写的正则匹配

1location / { 2 if ($http_user_agent ~* "python|curl|java|wget|httpclient|okhttp") { 3 return 503; 4 } 5 # 正常处理 6 # ... 7}

防盗链

1location ~* \.(gif|jpg|png|swf|flv)$ { 2 root html 3 valid_referers none blocked *.nginxcn.com; 4 if ($invalid_referer) { 5 rewrite ^/ www.nginx.cn 6 #return 404; 7 } 8}

虚拟目录配置

alias指定的目录是准确的,root是指定目录的上级目录,并且该上级目录要含有location指定名称的同名目录。

1location /img/ { 2 alias /var/www/image/; 3} 4# 访问/img/目录里面的文件时,ningx会自动去/var/www/image/目录找文件 5location /img/ { 6 root /var/www/image; 7} 8# 访问/img/目录下的文件时,nginx会去/var/www/image/img/目录下找文件。]

防盗图配置

1location ~ \/public\/(css|js|img)\/.*\.(js|css|gif|jpg|jpeg|png|bmp|swf) { 2 valid_referers none blocked *.jslite.io; 3 if ($invalid_referer) { 4 rewrite ^/ http://wangchujiang.com/piratesp.png; 5 } 6}

屏蔽.git等文件

1location ~ (.git|.gitattributes|.gitignore|.svn) { 2 deny all; 3}

域名路径加不加需要都能正常访问

1http://wangchujiang.com/api/index.php?a=1&name=wcj 2 ^ 有后缀 3 4http://wangchujiang.com/api/index?a=1&name=wcj 5 ^ 没有后缀

nginx rewrite规则如下:

1rewrite ^/(.*)/$ /index.php?/$1 permanent; 2if (!-d $request_filename){ 3 set $rule_1 1$rule_1; 4} 5if (!-f $request_filename){ 6 set $rule_1 2$rule_1; 7} 8if ($rule_1 = "21"){ 9 rewrite ^/ /index.php last; 10}

cockpit

https://github.com/cockpit-project/cockpit

1server{ 2    listen 80; 3    server_name cockpit.xxxxxxx.com; 4    return 301 https://$server_name$request_uri; 5} 6 7server { 8    listen 443 ssl; 9    server_name cockpit.xxxxxxx.com; 10 11    #ssl on; 12    ssl_certificate /etc/nginx/cert/cockpit.xxxxxxx.com.pem; 13    ssl_certificate_key /etc/nginx/cert/cockpit.xxxxxxx.com.key; 14 15    location / { 16        root /; 17        index index.html; 18        proxy_redirect off; 19        proxy_pass http://websocket; 20        proxy_http_version 1.1; 21        proxy_set_header Upgrade $http_upgrade; 22        proxy_set_header Connection "upgrade"; 23        proxy_set_header Host $http_host; 24    } 25}

这时输入域名,能看到登录页面,但登录后,显示不出内容,页面全白。这里要对 cockpit.conf 进行设置修改。

1sudo vim /etc/cockpit/cockpit.conf

参照如下配置修改,注意域名替换为 your_domain_host

1[WebService] 2Origins = https://cockpit.xxxxxxx.com https://127.0.0.1:9090 3ProtocolHeader = X-Forwarded-Proto 4AllowUnencrypted = true

错误问题

1The plain HTTP request was sent to HTTPS port

解决办法,fastcgi_param HTTPS $https if_not_empty 添加这条规则,

1server { 2 listen 443 ssl; # 注意这条规则 3 server_name my.domain.com; 4 5 fastcgi_param HTTPS $https if_not_empty; 6 fastcgi_param HTTPS on; 7 8 ssl_certificate /etc/ssl/certs/your.pem; 9 ssl_certificate_key /etc/ssl/private/your.key; 10 11 location / { 12 # Your config here... 13 } 14}

Nginx 模块

  • Nginx Office Hours 一个 nginx 模块,允许您仅在办公时间内提供访问访问网站。

精品文章参考

Contributors

As always, thanks to our amazing contributors!

<a href="https://github.com/jaywcjlove/nginx-tutorial/graphs/contributors"> <img src="https://jaywcjlove.github.io/nginx-tutorial/CONTRIBUTORS.svg" /> </a>

Made with action-contributors.

License

Licensed under the MIT License.

更多精彩教程请访问MacV.com网站!

点赞
收藏

评论区

加载中...

相关推荐

Keepalived+LVS+nginx搭建nginx高可用集群

       nginx是一款非常优秀的反向代理工具,支持请求分发,负载均衡,以及缓存等等非常实用的功能。在请求处理上,nginx采用的是epoll模型,这是一种基于事件监听的模型,因而其具备非常高效的请求处理效率,单机并发能力能够达到上百万。nginx接收到的请求可以通过负载均衡策略分发到其下一级的应用服务器,这些服务器一般是以集群方式部署的,因而在性能不

NGINX配置入门

Nginx是一个轻量级高性能的web服务器,它是为快速响应大量静态文件请求和高效利用系统资源而设计的。与apache使用面向进程或线程的方式处理请求不同,nginx使用异步事件驱动模型在负载下性能更突出。虽然nginx能高效地服务静态文件,但也有人认为nginx处理动态内容并不理想。不像apache服务器,nginx没用使用内嵌解释器的方式来处理动态内容

Nginx入门简介和反向代理、负载均衡、动静分离理解

场景Nginx简介Nginx("enginex")是一个高性能的HTTP和反向代理服务器特点是占有内存少,并发能力强,事实上nginx的并发能力确实在同类型的网页服务器中表现较好,中国大陆使用nginx网站用户有:百度、京东、新浪、网易、腾讯、淘宝等。Nginx可以作为静态页面的web服务器,

Nginx系列之Linux系统安装部署Nginx环境

1、什么是nginx?Nginx(enginex)是一个高性能的HTTP和反向代理web服务器,同时也提供了IMAP/POP3/SMTP服务。如图,nginx常被用于做代理!这里写图片描述(https://oscimg.oschina.net/oscnet/upde667b054d471beaa78cc5cf2a12a7b5.p

Nginx(Windows)

Nginx是一个高性能的HTTP和反向代理服务器,也是一个IMAP/POP3/SMTP服务器。反向代理方式是指以代理服务器来接受internet上的连接请求,然后将请求转发给内部网络上的服务器,并将从服务器上得到的结果返回给internet上请求连接的客户端,此时代理服务器对外就表现为一个反向代理服务器。比如我

Nginx入门

课程概览Nginx是一个开源的HTTP和反向代理服务器,同时也可以用于邮件代理服务器、负载均衡以及HTTP缓存。Nginx项目在一开始时,就定位于高并发、高性能以及低内存消耗的目标。它可以运行在Linux,,各类BSD系统,MacOSX,Solaris,AIX,HPUX以及各类\nix操作系统。此外,它也提供了一个Windows