{"id":13459285,"url":"https://github.com/jaywcjlove/nginx-tutorial","last_synced_at":"2025-05-16T05:03:12.719Z","repository":{"id":41067118,"uuid":"126048124","full_name":"jaywcjlove/nginx-tutorial","owner":"jaywcjlove","description":"Nginx安装维护入门学习笔记，以及各种实例。","archived":false,"fork":false,"pushed_at":"2024-12-19T06:05:50.000Z","size":289,"stargazers_count":1329,"open_issues_count":2,"forks_count":236,"subscribers_count":28,"default_branch":"master","last_synced_at":"2025-05-16T05:01:50.592Z","etag":null,"topics":["nginx","nginx-linux","nginx-server"],"latest_commit_sha":null,"homepage":"https://jaywcjlove.github.io/nginx-tutorial","language":null,"has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/jaywcjlove.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":".github/FUNDING.yml","license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null},"funding":{"ko_fi":"jaywcjlove","buy_me_a_coffee":"jaywcjlove","custom":["https://www.paypal.me/kennyiseeyou","https://jaywcjlove.github.io/#/sponsor"]}},"created_at":"2018-03-20T16:27:41.000Z","updated_at":"2025-05-11T03:35:56.000Z","dependencies_parsed_at":"2022-08-13T10:50:09.683Z","dependency_job_id":"5392f7ea-bbf2-4f93-865b-736cd3ebf595","html_url":"https://github.com/jaywcjlove/nginx-tutorial","commit_stats":{"total_commits":38,"total_committers":3,"mean_commits":"12.666666666666666","dds":"0.10526315789473684","last_synced_commit":"f9fc99a17635dc7bf9915da775de46e03fa106e1"},"previous_names":[],"tags_count":1,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/jaywcjlove%2Fnginx-tutorial","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/jaywcjlove%2Fnginx-tutorial/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/jaywcjlove%2Fnginx-tutorial/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/jaywcjlove%2Fnginx-tutorial/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/jaywcjlove","download_url":"https://codeload.github.com/jaywcjlove/nginx-tutorial/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":254471028,"owners_count":22076582,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["nginx","nginx-linux","nginx-server"],"created_at":"2024-07-31T09:01:14.193Z","updated_at":"2025-05-16T05:03:12.674Z","avatar_url":"https://github.com/jaywcjlove.png","language":null,"readme":"\u003cp align=\"center\"\u003e\n  \u003ca href=\"http://nginx.org/\"\u003e\n    \u003cimg width=\"160\" src=\"./favicon.svg\" /\u003e\n  \u003c/a\u003e\n\n\u003c/p\u003e\n\u003c!--rehype:style=height: 210px; display: flex; align-items: center; justify-content: center;--\u003e\n\u003c!--idoc:ignore:start--\u003e\n\u003ch1 align=\"center\"\u003eNginx 入门学习笔记\u003c/h1\u003e\n\u003c!--idoc:ignore:end--\u003e\n\n[![Buy me a coffee](https://img.shields.io/badge/Buy%20me%20a%20coffee-048754?logo=buymeacoffee)](https://jaywcjlove.github.io/#/sponsor)\n\n[Nginx](https://nginx.org/en/) 是一款面向性能设计的 HTTP 服务器，能反向代理 HTTP、HTTPS 和邮件相关（SMTP、POP3、IMAP）的协议链接，并且提供了负载均衡以及 HTTP 缓存。它的设计充分使用异步事件模型，削减上下文调度的开销，提高服务器并发能力。采用了模块化设计，提供了丰富的第三方模块。\n\n关于 Nginx，有这些标签：「异步」「事件」「模块化」「高性能」「高并发」「反向代理」「负载均衡」\n\nLinux系统：`Centos 7 x64`  \nNginx版本：`1.11.5`\n\n\u003c!--idoc:ignore:start--\u003e\n\n## 目录\n\n- [安装](#安装)\t\n  - [安装依赖](#安装依赖)\t\n  - [下载](#下载)\t\n  - [编译安装](#编译安装)\t\n  - [Nginx 测试](#nginx-测试)\t\n  - [设置全局 nginx 命令](#设置全局-nginx-命令)\t\n- [Mac 安装](#mac-安装)\t\n  - [安装nginx](#安装nginx)\t\n  - [启动服务](#启动服务)\t\n- [开机自启动](#开机自启动)\t\n- [运维](#运维)\t\n  - [服务管理](#服务管理)\t\n  - [重启服务防火墙报错解决](#重启服务防火墙报错解决)\t\n- [Nginx 卸载](#nginx-卸载)\t\n- [参数说明](#参数说明)\t\n- [配置](#配置)\t\n  - [常用正则](#常用正则)\t\n  - [全局变量](#全局变量)\t\n  - [符号参考](#符号参考)\t\n  - [配置文件](#配置文件)\t\n  - [内置预定义变量](#内置预定义变量)\t\n  - [反向代理](#反向代理)\t\n  - [负载均衡](#负载均衡)\t\n    - [RR](#rr)\t\n    - [权重](#权重)\t\n    - [ip_hash](#ip_hash)\t\n    - [fair](#fair)\t\n    - [url_hash](#url_hash)\t\n  - [屏蔽ip](#屏蔽ip)\t\n- [第三方模块安装方法](#第三方模块安装方法)\t\n- [重定向](#重定向)\t\n  - [重定向整个网站](#重定向整个网站)\t\n  - [重定向单页](#重定向单页)\t\n  - [重定向整个子路径](#重定向整个子路径)\t\n- [性能](#性能)\t\n  - [内容缓存](#内容缓存)\t\n  - [Gzip压缩](#gzip压缩)\t\n  - [打开文件缓存](#打开文件缓存)\t\n  - [SSL缓存](#ssl缓存)\t\n  - [上游Keepalive](#上游keepalive)\t\n  - [监控](#监控)\t\n- [常见使用场景](#常见使用场景)\t\n  - [跨域问题](#跨域问题)\t\n  - [跳转到带www的域上面](#跳转到带www的域上面)\t\n  - [代理转发](#代理转发)\t\n  - [监控状态信息](#监控状态信息)\t\n  - [代理转发连接替换](#代理转发连接替换)\t\n  - [SSL 配置](#ssl-配置)\t\n  - [强制将http重定向到https](#强制将http重定向到https)\t\n  - [两个虚拟主机](#两个虚拟主机)\t\n  - [虚拟主机标准配置](#虚拟主机标准配置)\t\n  - [爬虫过滤](#爬虫过滤)\t\n  - [防盗链](#防盗链)\t\n  - [虚拟目录配置](#虚拟目录配置)\t\n  - [防盗图配置](#防盗图配置)\t\n  - [屏蔽.git等文件](#屏蔽git等文件)\t\n  - [域名路径加不加需要都能正常访问](#域名路径加不加需要都能正常访问)\t\n  - [cockpit](#cockpit)\t\n- [错误问题](#错误问题)\t\n- [精品文章参考](#精品文章参考)\n\n\u003c!--idoc:ignore:end--\u003e\n\n## 安装\n\n### 安装依赖\n\n\u003e prce（重定向支持）和 openssl（https 支持，如果不需要 https 可以不安装）。\n\n```bash\nyum install -y pcre-devel \nyum -y install gcc make gcc-c++ wget\nyum -y install openssl openssl-devel \n```\n\n在 CentOS 6.5 上安装时，我选择了“基本服务器”，默认情况下这两个包都没有安装全，所以需要运行上述命令进行安装。\n\n### 下载\n\n[nginx 的所有版本在这里](http://nginx.org/download/)\n\n```bash\nwget http://nginx.org/download/nginx-1.13.3.tar.gz\nwget http://nginx.org/download/nginx-1.13.7.tar.gz\n\n# 如果没有安装 wget\n$ yum install wget\n\n# 解压压缩包\ntar zxf nginx-1.13.3.tar.gz\n```\n\n### 编译安装\n\n然后进入目录编译安装，[configure参数说明](#参数说明)\n\n```bash\ncd nginx-1.11.5\n./configure\n\n....\nConfiguration summary\n  + using system PCRE library\n  + OpenSSL library is not used\n  + using system zlib library\n\n  nginx path prefix: \"/usr/local/nginx\"\n  nginx binary file: \"/usr/local/nginx/sbin/nginx\"\n  nginx modules path: \"/usr/local/nginx/modules\"\n  nginx configuration prefix: \"/usr/local/nginx/conf\"\n  nginx configuration file: \"/usr/local/nginx/conf/nginx.conf\"\n  nginx pid file: \"/usr/local/nginx/logs/nginx.pid\"\n  nginx error log file: \"/usr/local/nginx/logs/error.log\"\n  nginx http access log file: \"/usr/local/nginx/logs/access.log\"\n  nginx http client request body temporary files: \"client_body_temp\"\n  nginx http proxy temporary files: \"proxy_temp\"\n  nginx http fastcgi temporary files: \"fastcgi_temp\"\n  nginx http uwsgi temporary files: \"uwsgi_temp\"\n  nginx http scgi temporary files: \"scgi_temp\"\n```\n\n安装报错误的话比如：“C compiler cc is not found”，这个就是缺少编译环境，安装一下就可以了 **yum -y install gcc make gcc-c++ openssl-devel**\n\n如果没有error信息，就可以执行下边的安装了：\n\n```bash\nmake\nmake install\n```\n\n### Nginx 测试\n\n运行下面命令会出现两个结果，一般情况nginx会安装在`/usr/local/nginx`目录中\n\n```bash\ncd /usr/local/nginx/sbin/\n./nginx -t\n\n# nginx: the configuration file /usr/local/nginx/conf/nginx.conf syntax is ok\n# nginx: configuration file /usr/local/nginx/conf/nginx.conf test is successful\n```\n\n### 设置全局 Nginx 命令\n\n```bash\nvi ~/.bash_profile\n```\n\n将下面内容添加到 `~/.bash_profile` 文件中\n\n```bash\nPATH=$PATH:$HOME/bin:/usr/local/nginx/sbin/\nexport PATH\n```\n\n运行命令 **`source ~/.bash_profile`** 让配置立即生效。你就可以全局运行 `nginx` 命令了。\n\n## Mac 安装\n\nMac OSX 安装特别简单，首先你需要安装 [Brew](https://brew.sh/)， 通过 `brew` 快速安装 `nginx`。\n\n### 安装nginx\n\n```bash\nbrew install nginx\n# Updating Homebrew...\n# ==\u003e Auto-updated Homebrew!\n# Updated 2 taps (homebrew/core, homebrew/cask).\n# ==\u003e Updated Formulae\n# ==\u003e Installing dependencies for nginx: openssl, pcre\n# ==\u003e Installing nginx dependency: openssl\n# ==\u003e Downloading https://homebrew.bintray.com/bottles/openssl-1.0.2o_1.high_sierra.bottle.tar.gz\n# ######################################################################## 100.0%\n# ==\u003e Pouring openssl-1.0.2o_1.high_sierra.bottle.tar.gz\n# ==\u003e Caveats\n# A CA file has been bootstrapped using certificates from the SystemRoots\n# keychain. To add additional certificates (e.g. the certificates added in\n# the System keychain), place .pem files in\n#   /usr/local/etc/openssl/certs\n# \n# and run\n#   /usr/local/opt/openssl/bin/c_rehash\n# \n# This formula is keg-only, which means it was not symlinked into /usr/local,\n# because Apple has deprecated use of OpenSSL in favor of its own TLS and crypto libraries.\n# \n# If you need to have this software first in your PATH run:\n#   echo 'export PATH=\"/usr/local/opt/openssl/bin:$PATH\"' \u003e\u003e ~/.zshrc\n# \n# For compilers to find this software you may need to set:\n#     LDFLAGS:  -L/usr/local/opt/openssl/lib\n#     CPPFLAGS: -I/usr/local/opt/openssl/include\n# For pkg-config to find this software you may need to set:\n#     PKG_CONFIG_PATH: /usr/local/opt/openssl/lib/pkgconfig\n# \n# ==\u003e Summary\n# 🍺  /usr/local/Cellar/openssl/1.0.2o_1: 1,791 files, 12.3MB\n# ==\u003e Installing nginx dependency: pcre\n# ==\u003e Downloading https://homebrew.bintray.com/bottles/pcre-8.42.high_sierra.bottle.tar.gz\n# ######################################################################## 100.0%\n# ==\u003e Pouring pcre-8.42.high_sierra.bottle.tar.gz\n# 🍺  /usr/local/Cellar/pcre/8.42: 204 files, 5.3MB\n# ==\u003e Installing nginx\n# ==\u003e Downloading https://homebrew.bintray.com/bottles/nginx-1.13.12.high_sierra.bottle.tar.gz\n# ######################################################################## 100.0%\n# ==\u003e Pouring nginx-1.13.12.high_sierra.bottle.tar.gz\n# ==\u003e Caveats\n# Docroot is: /usr/local/var/www\n# \n# The default port has been set in /usr/local/etc/nginx/nginx.conf to 8080 so that\n# nginx can run without sudo.\n# \n# nginx will load all files in /usr/local/etc/nginx/servers/.\n# \n# To have launchd start nginx now and restart at login:\n#   brew services start nginx\n# Or, if you don't wacd /usr/local/Cellar/nginx/1.13.12/n just run:\n# cd /usr/local/Cellar/nginx/1.13.12/\n```\n\n### 启动服务\n\n注意默认端口不是 `8080` 查看确认端口是否被占用。\n\n```bash\nbrew services start nginx\n# http://localhost:8080/\n```\n\n## 开机自启动\n\n**开机自启动方法一：**\n\n编辑 **vi /lib/systemd/system/nginx.service** 文件，没有创建一个 **touch nginx.service** 然后将如下内容根据具体情况进行修改后，添加到nginx.service文件中：\n\n```bash\n[Unit]\nDescription=nginx\nAfter=network.target remote-fs.target nss-lookup.target\n\n[Service]\n\nType=forking\nPIDFile=/var/run/nginx.pid\nExecStartPre=/usr/local/nginx/sbin/nginx -t -c /usr/local/nginx/conf/nginx.conf\nExecStart=/usr/local/nginx/sbin/nginx -c /usr/local/nginx/conf/nginx.conf\nExecReload=/bin/kill -s HUP $MAINPID\nExecStop=/bin/kill -s QUIT $MAINPID\nPrivateTmp=true\n\n[Install]\nWantedBy=multi-user.target\n```\n\n- `[Unit]`:服务的说明  \n- `Description`:描述服务  \n- `After`:描述服务类别  \n- `[Service]`服务运行参数的设置  \n- `Type=forking`是后台运行的形式  \n- `ExecStart`为服务的具体运行命令  \n- `ExecReload`为重启命令  \n- `ExecStop`为停止命令  \n- `PrivateTmp=True`表示给服务分配独立的临时空间  \n\n注意：`[Service]`的启动、重启、停止命令全部要求使用绝对路径。\n\n`[Install]`运行级别下服务安装的相关设置，可设置为多用户，即系统运行级别为`3`。\n\n保存退出。\n\n设置开机启动，使配置生效：\n\n```bash\n# 启动nginx服务\nsystemctl start nginx.service\n# 停止开机自启动\nsystemctl disable nginx.service\n# 查看服务当前状态\nsystemctl status nginx.service\n# 查看所有已启动的服务\nsystemctl list-units --type=service\n# 重新启动服务\nsystemctl restart nginx.service\n# 设置开机自启动\nsystemctl enable nginx.service\n# 输出下面内容表示成功了\nCreated symlink from /etc/systemd/system/multi-user.target.wants/nginx.service to /usr/lib/systemd/system/nginx.service.\n```\n\n```bash\nsystemctl is-enabled servicename.service # 查询服务是否开机启动\nsystemctl enable *.service  # 开机运行服务\nsystemctl disable *.service # 取消开机运行\nsystemctl start *.service   # 启动服务\nsystemctl stop *.service    # 停止服务\nsystemctl restart *.service # 重启服务\nsystemctl reload *.service  # 重新加载服务配置文件\nsystemctl status *.service  # 查询服务运行状态\nsystemctl --failed # 显示启动失败的服务\n```\n\n注：*代表某个服务的名字，如http的服务名为httpd\n\n**开机自启动方法二：**\n\n```bash\nvi /etc/rc.local\n\n# 在 rc.local 文件中，添加下面这条命令\n/usr/local/nginx/sbin/nginx start\n```\n\n如果开机后发现自启动脚本没有执行，你要去确认一下rc.local这个文件的访问权限是否是可执行的，因为rc.local默认是不可执行的。修改rc.local访问权限，增加可执行权限：\n\n```bash\n# /etc/rc.local是/etc/rc.d/rc.local的软连接，\nchmod +x /etc/rc.d/rc.local\n```\n\n官方脚本 [ed Hat NGINX Init Script](https://www.nginx.com/resources/wiki/start/topics/examples/redhatnginxinit/)。\n\n## 运维\n\n### 服务管理\n\n```bash\n# 启动\n/usr/local/nginx/sbin/nginx\n# 重启\n/usr/local/nginx/sbin/nginx -s reload\n# 关闭进程\n/usr/local/nginx/sbin/nginx -s stop\n# 平滑关闭nginx\n/usr/local/nginx/sbin/nginx -s quit\n# 查看nginx的安装状态，\n/usr/local/nginx/sbin/nginx -V \n```\n\n**关闭防火墙，或者添加防火墙规则就可以测试了**\n\n```bash\nservice iptables stop\n```\n\n或者编辑配置文件：\n\n```bash\nvi /etc/sysconfig/iptables\n```\n\n添加这样一条开放80端口的规则后保存：\n\n```bash\n-A INPUT -m state --state NEW -m tcp -p tcp --dport 80 -j ACCEPT\n```\n\n重启服务即可:\n\n```bash\nservice iptables restart\n# 命令进行查看目前nat\niptables -t nat -L\n```\n\n### 重启服务防火墙报错解决\n\n\n```bash\nservice iptables restart\n# Redirecting to /bin/systemctl restart  iptables.service\n# Failed to restart iptables.service: Unit iptables.service failed to load: No such file or directory.\n```\n\n在CentOS 7或RHEL 7或Fedora中防火墙由 **firewalld** 来管理，当然你可以还原传统的管理方式。或则使用新的命令进行管理。\n假如采用传统请执行一下命令：\n\n```bash\n# 传统命令\nsystemctl stop firewalld\nsystemctl mask firewalld\n```\n\n```bash\n# 安装命令\nyum install iptables-services\n\nsystemctl enable iptables \nservice iptables restart\n```\n\n\n## Nginx 卸载\n\n如果通过yum安装，使用下面命令安装。\n\n```bash\nyum remove nginx\n```\n\n编译安装，删除/usr/local/nginx目录即可\n如果配置了自启动脚本，也需要删除。\n\n\n## 参数说明\n\n| 参数 | 说明 |\n| ---- | ---- |\n| --prefix=`\u003cpath\u003e` | Nginx安装路径。如果没有指定，默认为 /usr/local/nginx。 |\n| --sbin-path=`\u003cpath\u003e` | Nginx可执行文件安装路径。只能安装时指定，如果没有指定，默认为`\u003cprefix\u003e`/sbin/nginx。 |\n| --conf-path=`\u003cpath\u003e` | 在没有给定-c选项下默认的nginx.conf的路径。如果没有指定，默认为`\u003cprefix\u003e`/conf/nginx.conf。 |\n| --pid-path=`\u003cpath\u003e` | 在nginx.conf中没有指定pid指令的情况下，默认的nginx.pid的路径。如果没有指定，默认为 `\u003cprefix\u003e`/logs/nginx.pid。 |\n| --lock-path=`\u003cpath\u003e` | nginx.lock文件的路径。 |\n| --error-log-path=`\u003cpath\u003e` | 在nginx.conf中没有指定error_log指令的情况下，默认的错误日志的路径。如果没有指定，默认为 `\u003cprefix\u003e`/- logs/error.log。 |\n| --http-log-path=`\u003cpath\u003e` | 在nginx.conf中没有指定access_log指令的情况下，默认的访问日志的路径。如果没有指定，默认为 `\u003cprefix\u003e`/- logs/access.log。 |\n| --user=`\u003cuser\u003e` | 在nginx.conf中没有指定user指令的情况下，默认的nginx使用的用户。如果没有指定，默认为 nobody。 |\n| --group=`\u003cgroup\u003e` | 在nginx.conf中没有指定user指令的情况下，默认的nginx使用的组。如果没有指定，默认为 nobody。 |\n| --builddir=DIR | 指定编译的目录 |\n| --with-rtsig_module | 启用 rtsig 模块 |\n| --with-select_module --without-select_module | 允许或不允许开启SELECT模式，如果 configure 没有找到更合适的模式，比如：kqueue(sun os),epoll (linux kenel 2.6+), rtsig(- 实时信号)或者/dev/poll(一种类似select的模式，底层实现与SELECT基本相 同，都是采用轮训方法) SELECT模式将是默认安装模式|\n| --with-poll_module --without-poll_module | Whether 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. |\n| --with-http_ssl_module | Enable 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  |\n| --with-http_realip_module | 启用 ngx_http_realip_module |\n| --with-http_addition_module | 启用 ngx_http_addition_module |\n| --with-http_sub_module | 启用 ngx_http_sub_module |\n| --with-http_dav_module | 启用 ngx_http_dav_module |\n| --with-http_flv_module | 启用 ngx_http_flv_module |\n| --with-http_stub_status_module | 启用 \"server status\" 页 |\n| --without-http_charset_module | 禁用 ngx_http_charset_module |\n| --without-http_gzip_module | 禁用 ngx_http_gzip_module. 如果启用，需要 zlib 。 |\n| --without-http_ssi_module | 禁用 ngx_http_ssi_module |\n| --without-http_userid_module | 禁用 ngx_http_userid_module |\n| --without-http_access_module | 禁用 ngx_http_access_module |\n| --without-http_auth_basic_module | 禁用 ngx_http_auth_basic_module |\n| --without-http_autoindex_module | 禁用 ngx_http_autoindex_module |\n| --without-http_geo_module | 禁用 ngx_http_geo_module |\n| --without-http_map_module | 禁用 ngx_http_map_module |\n| --without-http_referer_module | 禁用 ngx_http_referer_module |\n| --without-http_rewrite_module | 禁用 ngx_http_rewrite_module. 如果启用需要 PCRE 。 |\n| --without-http_proxy_module | 禁用 ngx_http_proxy_module |\n| --without-http_fastcgi_module | 禁用 ngx_http_fastcgi_module |\n| --without-http_memcached_module | 禁用 ngx_http_memcached_module |\n| --without-http_limit_zone_module | 禁用 ngx_http_limit_zone_module |\n| --without-http_empty_gif_module | 禁用 ngx_http_empty_gif_module |\n| --without-http_browser_module | 禁用 ngx_http_browser_module |\n| --without-http_upstream_ip_hash_module | 禁用 ngx_http_upstream_ip_hash_module |\n| --with-http_perl_module | 启用 ngx_http_perl_module |\n| --with-perl_modules_path=PATH | 指定 perl 模块的路径 |\n| --with-perl=PATH | 指定 perl 执行文件的路径 |\n| --http-log-path=PATH | Set path to the http access log |\n| --http-client-body-temp-path=PATH | Set path to the http client request body temporary files |\n| --http-proxy-temp-path=PATH | Set path to the http proxy temporary files |\n| --http-fastcgi-temp-path=PATH | Set path to the http fastcgi temporary files |\n| --without-http | 禁用 HTTP server |\n| --with-mail | 启用 IMAP4/POP3/SMTP 代理模块 |\n| --with-mail_ssl_module | 启用 ngx_mail_ssl_module |\n| --with-cc=PATH | 指定 C 编译器的路径 |\n| --with-cpp=PATH | 指定 C 预处理器的路径 |\n| --with-cc-opt=OPTIONS | Additional 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\". |\n| --with-ld-opt=OPTIONS | Additional 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\". |\n| --with-cpu-opt=CPU | 为特定的 CPU 编译，有效的值包括：pentium, pentiumpro, pentium3, pentium4, athlon, opteron, amd64, sparc32, sparc64, ppc64 |\n| --without-pcre | 禁止 PCRE 库的使用。同时也会禁止 HTTP rewrite 模块。在 \"location\" 配置指令中的正则表达式也需要 PCRE 。 |\n| --with-pcre=DIR | 指定 PCRE 库的源代码的路径。 |\n| --with-pcre-opt=OPTIONS | Set additional options for PCRE building. |\n| --with-md5=DIR | Set path to md5 library sources. |\n| --with-md5-opt=OPTIONS | Set additional options for md5 building. |\n| --with-md5-asm | Use md5 assembler sources. |\n| --with-sha1=DIR | Set path to sha1 library sources. |\n| --with-sha1-opt=OPTIONS | Set additional options for sha1 building. |\n| --with-sha1-asm | Use sha1 assembler sources. |\n| --with-zlib=DIR | Set path to zlib library sources. |\n| --with-zlib-opt=OPTIONS | Set additional options for zlib building. |\n| --with-zlib-asm=CPU | Use zlib assembler sources optimized for specified CPU, valid values are: pentium, pentiumpro |\n| --with-openssl=DIR | Set path to OpenSSL library sources |\n| --with-openssl-opt=OPTIONS | Set additional options for OpenSSL building |\n| --with-debug | 启用调试日志 |\n| --add-module=PATH | Add in a third-party module found in directory PATH |\n\n\n## 配置\n\n在Centos 默认配置文件在 **/usr/local/nginx-1.5.1/conf/nginx.conf** 我们要在这里配置一些文件。nginx.conf是主配置文件，由若干个部分组成，每个大括号`{}`表示一个部分。每一行指令都由分号结束`;`，标志着一行的结束。\n\n### 常用正则\n\n| 正则 | 说明 | 正则 | 说明 |\n| ---- | ---- | ---- | ---- | \n| `. ` | 匹配除换行符以外的任意字符 | `$ ` | 匹配字符串的结束 |\n| `? ` | 重复0次或1次 | `{n} ` | 重复n次 |\n| `+ ` | 重复1次或更多次 | `{n,} ` | 重复n次或更多次 |\n| `*` | 重复0次或更多次 | `[c] ` | 匹配单个字符c |\n| `\\d ` |匹配数字 | `[a-z]` | 匹配a-z小写字母的任意一个 |\n| `^ ` | 匹配字符串的开始 | - | - |\n\n### 全局变量\n\n| 变量 | 说明 | 变量 | 说明 |\n| ---- | ---- | ---- | ---- | \n| $args | 这个变量等于请求行中的参数，同$query_string | $remote_port | 客户端的端口。 |\n| $content_length | 请求头中的Content-length字段。 | $remote_user | 已经经过Auth Basic Module验证的用户名。 |\n| $content_type | 请求头中的Content-Type字段。 | $request_filename | 当前请求的文件路径，由root或alias指令与URI请求生成。 |\n| $document_root | 当前请求在root指令中指定的值。 | $scheme | HTTP方法（如http，https）。 |\n| $host | 请求主机头字段，否则为服务器名称。 | $server_protocol | 请求使用的协议，通常是HTTP/1.0或HTTP/1.1。 |\n| $http_user_agent | 客户端agent信息 | $server_addr | 服务器地址，在完成一次系统调用后可以确定这个值。 |\n| $http_cookie | 客户端cookie信息 | $server_name | 服务器名称。 |\n| $limit_rate | 这个变量可以限制连接速率。 | $server_port | 请求到达服务器的端口号。 |\n| $request_method | 客户端请求的动作，通常为GET或POST。 | $request_uri | 包含请求参数的原始URI，不包含主机名，如：/foo/bar.php?arg=baz。 |\n| $remote_addr | 客户端的IP地址。 | $uri | 不带请求参数的当前URI，$uri不包含主机名，如/foo/bar.html。 |\n| $document_uri | 与$uri相同。 | - | - |\n\n例如请求：`http://localhost:3000/test1/test2/test.php`\n\n```\n$host：localhost  \n$server_port：3000  \n$request_uri：/test1/test2/test.php  \n$document_uri：/test1/test2/test.php  \n$document_root：/var/www/html  \n$request_filename：/var/www/html/test1/test2/test.php  \n```\n\n### 符号参考\n\n| 符号 | 说明 | 符号 | 说明 | 符号 | 说明 |\n| ---- | ---- | ---- | ---- | ---- | ---- |\n| k,K | 千字节 | m,M | 兆字节 | ms | 毫秒 |\n| s | 秒 | m | 分钟 | h |  小时 |\n| d | 日 | w | 周 | M |  一个月, 30天 |\n\n例如，\"8k\"，\"1m\" 代表字节数计量。  \n例如，\"1h 30m\"，\"1y 6M\"。代表 \"1小时 30分\"，\"1年零6个月\"。 \n\n### 配置文件\n\nnginx 的配置系统由一个主配置文件和其他一些辅助的配置文件构成。这些配置文件均是纯文本文件，全部位于 nginx 安装目录下的 conf 目录下。\n\n指令由 nginx 的各个模块提供，不同的模块会提供不同的指令来实现配置。\n指令除了 Key-Value 的形式，还有作用域指令。\n\nnginx.conf 中的配置信息，根据其逻辑上的意义，对它们进行了分类，也就是分成了多个作用域，或者称之为配置指令上下文。不同的作用域含有一个或者多个配置项。\n\n下面的这些上下文指令是用的比较多：\n\n| Directive |  Description | Contains Directive |\n| ---- | ---- | ---- |\n| main  |  nginx 在运行时与具体业务功能（比如 http 服务或者 email 服务代理）无关的一些参数，比如工作进程数，运行的身份等。 | user, worker_processes, error_log, events, http, mail |\n| http  |  与提供 http 服务相关的一些配置参数。例如：是否使用 keepalive 啊，是否使用 gzip 进行压缩等。 |  server |\n| server | http 服务上支持若干虚拟主机。每个虚拟主机一个对应的 server 配置项，配置项里面包含该虚拟主机相关的配置。在提供 mail 服务的代理时，也可以建立若干 server. 每个 server 通过监听的地址来区分。| listen, server_name, access_log, location, protocol, proxy, smtp_auth, xclient |\n| location  |  http 服务中，某些特定的 URL 对应的一系列配置项。  | index, root |\n| mail | 实现 email 相关的 SMTP/IMAP/POP3 代理时，共享的一些配置项（因为可能实现多个代理，工作在多个监听地址上）。 | server, http, imap_capabilities |\n| include | 以便增强配置文件的可读性，使得部分配置文件可以重新使用。 | - |\n| valid_referers | 用来校验Http请求头Referer是否有效。 | - |\n| try_files | 用在server部分，不过最常见的还是用在location部分，它会按照给定的参数顺序进行尝试，第一个被匹配到的将会被使用。 | - |\n| if | 当在location块中使用if指令，在某些情况下它并不按照预期运行，一般来说避免使用if指令。 | - |\n\n\n例如我们再 **nginx.conf** 里面引用两个配置 vhost/example.com.conf 和 vhost/gitlab.com.conf 它们都被放在一个我自己新建的目录 vhost 下面。nginx.conf 配置如下：\n\n```nginx\nworker_processes  1;\nevents {\n    worker_connections  1024;\n}\n\nhttp {\n    include       mime.types;\n    default_type  application/octet-stream;\n\n    #log_format  main  '$remote_addr - $remote_user [$time_local] \"$request\" '\n    #                  '$status $body_bytes_sent \"$http_referer\" '\n    #                  '\"$http_user_agent\" \"$http_x_forwarded_for\"';\n\n    #access_log  logs/access.log  main;\n\n    sendfile        on;\n    #tcp_nopush     on;\n\n    #keepalive_timeout  0;\n    keepalive_timeout  65;\n\n    #gzip  on;\n    server {\n        listen       80;\n        server_name  localhost;\n        location / {\n            root   html;\n            index  index.html index.htm;\n        }\n        error_page   500 502 503 504  /50x.html;\n        location = /50x.html {\n            root   html;\n        }\n    }\n    include  vhost/example.com.conf;\n    include  vhost/gitlab.com.conf;\n}\n```\n\n\n简单的配置: example.com.conf\n\n```nginx\nserver {\n    #侦听的80端口\n    listen       80;\n    server_name  baidu.com app.baidu.com; # 这里指定域名\n    index        index.html index.htm;    # 这里指定默认入口页面\n    root /home/www/app.baidu.com;         # 这里指定目录\n}\n```\n\n### 内置预定义变量\n\nNginx提供了许多预定义的变量，也可以通过使用set来设置变量。你可以在if中使用预定义变量，也可以将它们传递给代理服务器。以下是一些常见的预定义变量，[更多详见](http://nginx.org/en/docs/varindex.html)\n\n| 变量名称  |  值 |\n| ----  | ---- |\n| $args_name | 在请求中的name参数 |\n| $args      | 所有请求参数 |\n| $query_string   | $args的别名 |\n| $content_length | 请求头Content-Length的值 |\n| $content_type   | 请求头Content-Type的值 |\n| $host |  如果当前有Host，则为请求头Host的值；如果没有这个头，那么该值等于匹配该请求的server_name的值 |\n| $remote_addr  |  客户端的IP地址 |\n| $request      |  完整的请求，从客户端收到，包括Http请求方法、URI、Http协议、头、请求体 |\n| $request_uri  |  完整请求的URI，从客户端来的请求，包括参数 |\n| $scheme | 当前请求的协议 |\n| $uri    | 当前请求的标准化URI |\n\n### 反向代理\n\n反向代理是一个Web服务器，它接受客户端的连接请求，然后将请求转发给上游服务器，并将从服务器得到的结果返回给连接的客户端。下面简单的反向代理的例子：\n\n```nginx\nserver {  \n  listen       80;                                                        \n  server_name  localhost;                                              \n  client_max_body_size 1024M;  # 允许客户端请求的最大单文件字节数\n\n  location / {\n    proxy_pass                         http://localhost:8080;\n    proxy_set_header Host              $host:$server_port;\n    proxy_set_header X-Forwarded-For   $remote_addr; # HTTP的请求端真实的IP\n    proxy_set_header X-Forwarded-Proto $scheme;      # 为了正确地识别实际用户发出的协议是 http 还是 https\n  }\n}\n```\n\n复杂的配置: gitlab.com.conf。\n\n```nginx\nserver {\n    #侦听的80端口\n    listen       80;\n    server_name  git.example.cn;\n    location / {\n        proxy_pass   http://localhost:3000;\n        #以下是一些反向代理的配置可删除\n        proxy_redirect             off;\n        #后端的Web服务器可以通过X-Forwarded-For获取用户真实IP\n        proxy_set_header           Host $host;\n        client_max_body_size       10m; #允许客户端请求的最大单文件字节数\n        client_body_buffer_size    128k; #缓冲区代理缓冲用户端请求的最大字节数\n        proxy_connect_timeout      300; #nginx跟后端服务器连接超时时间(代理连接超时)\n        proxy_send_timeout         300; #后端服务器数据回传时间(代理发送超时)\n        proxy_read_timeout         300; #连接成功后，后端服务器响应时间(代理接收超时)\n        proxy_buffer_size          4k; #设置代理服务器（nginx）保存用户头信息的缓冲区大小\n        proxy_buffers              4 32k; #proxy_buffers缓冲区，网页平均在32k以下的话，这样设置\n        proxy_busy_buffers_size    64k; #高负荷下缓冲大小（proxy_buffers*2）\n    }\n}\n```\n\n代理到上游服务器的配置中，最重要的是proxy_pass指令。以下是代理模块中的一些常用指令：\n\n| 指令 | 说明 |\n| ---- | ---- |\n| proxy_connect_timeout  | Nginx从接受请求至连接到上游服务器的最长等待时间 |\n| proxy_send_timeout  | 后端服务器数据回传时间(代理发送超时) |\n| proxy_read_timeout  | 连接成功后，后端服务器响应时间(代理接收超时) |\n| proxy_cookie_domain | 替代从上游服务器来的Set-Cookie头的domain属性 |\n| proxy_cookie_path   | 替代从上游服务器来的Set-Cookie头的path属性 |\n| proxy_buffer_size   | 设置代理服务器（nginx）保存用户头信息的缓冲区大小 |\n| proxy_buffers       | proxy_buffers缓冲区，网页平均在多少k以下 |\n| proxy_set_header    | 重写发送到上游服务器头的内容，也可以通过将某个头部的值设置为空字符串，而不发送某个头部的方法实现 |\n| proxy_ignore_headers | 这个指令禁止处理来自代理服务器的应答。 | \n| proxy_intercept_errors | 使nginx阻止HTTP应答代码为400或者更高的应答。 | \n\n### 负载均衡\n\nupstream指令启用一个新的配置区段，在该区段定义一组上游服务器。这些服务器可能被设置不同的权重，也可能出于对服务器进行维护，标记为down。\n\n```nginx\nupstream gitlab {\n    ip_hash;\n    # upstream的负载均衡，weight是权重，可以根据机器配置定义权重。weigth参数表示权值，权值越高被分配到的几率越大。\n    server 192.168.122.11:8081 ;\n    server 127.0.0.1:82 weight=3;\n    server 127.0.0.1:83 weight=3 down;\n    server 127.0.0.1:84 weight=3; max_fails=3  fail_timeout=20s;\n    server 127.0.0.1:85 weight=4;;\n    keepalive 32;\n}\nserver {\n    #侦听的80端口\n    listen       80;\n    server_name  git.example.cn;\n    location / {\n        proxy_pass   http://gitlab;    #在这里设置一个代理，和upstream的名字一样\n        #以下是一些反向代理的配置可删除\n        proxy_redirect             off;\n        #后端的Web服务器可以通过X-Forwarded-For获取用户真实IP\n        proxy_set_header           Host $host;\n        proxy_set_header           X-Real-IP $remote_addr;\n        proxy_set_header           X-Forwarded-For $proxy_add_x_forwarded_for;\n        client_max_body_size       10m;  #允许客户端请求的最大单文件字节数\n        client_body_buffer_size    128k; #缓冲区代理缓冲用户端请求的最大字节数\n        proxy_connect_timeout      300;  #nginx跟后端服务器连接超时时间(代理连接超时)\n        proxy_send_timeout         300;  #后端服务器数据回传时间(代理发送超时)\n        proxy_read_timeout         300;  #连接成功后，后端服务器响应时间(代理接收超时)\n        proxy_buffer_size          4k; #设置代理服务器（nginx）保存用户头信息的缓冲区大小\n        proxy_buffers              4 32k;# 缓冲区，网页平均在32k以下的话，这样设置\n        proxy_busy_buffers_size    64k; #高负荷下缓冲大小（proxy_buffers*2）\n        proxy_temp_file_write_size 64k; #设定缓存文件夹大小，大于这个值，将从upstream服务器传\n    }\n}\n```\n\n每个请求按时间顺序逐一分配到不同的后端服务器，如果后端服务器down掉，能自动剔除。\n\n**负载均衡：**\n\nupstream模块能够使用3种负载均衡算法：轮询、IP哈希、最少连接数。\n\n**轮询：** 默认情况下使用轮询算法，不需要配置指令来激活它，它是基于在队列中谁是下一个的原理确保访问均匀地分布到每个上游服务器；  \n**IP哈希：** 通过ip_hash指令来激活，Nginx通过IPv4地址的前3个字节或者整个IPv6地址作为哈希键来实现，同一个IP地址总是能被映射到同一个上游服务器；  \n**最少连接数：** 通过least_conn指令来激活，该算法通过选择一个活跃数最少的上游服务器进行连接。如果上游服务器处理能力不同，可以通过给server配置weight权重来说明，该算法将考虑到不同服务器的加权最少连接数。\n\n#### RR\n\n**简单配置** ，这里我配置了2台服务器，当然实际上是一台，只是端口不一样而已，而8081的服务器是不存在的，也就是说访问不到，但是我们访问 `http://localhost` 的时候，也不会有问题，会默认跳转到`http://localhost:8080`具体是因为Nginx会自动判断服务器的状态，如果服务器处于不能访问（服务器挂了），就不会跳转到这台服务器，所以也避免了一台服务器挂了影响使用的情况，由于Nginx默认是RR策略，所以我们不需要其他更多的设置\n\n```nginx\nupstream test {\n    server localhost:8080;\n    server localhost:8081;\n}\nserver {\n    listen       81;\n    server_name  localhost;\n    client_max_body_size 1024M;\n \n    location / {\n        proxy_pass http://test;\n        proxy_set_header Host $host:$server_port;\n    }\n}\n```\n\n**负载均衡的核心代码为** \n\n```nginx\nupstream test {\n    server localhost:8080;\n    server localhost:8081;\n}\n```\n\n#### 权重\n\n指定轮询几率，weight和访问比率成正比，用于后端服务器性能不均的情况。 例如\n\n```nginx\nupstream test {\n    server localhost:8080 weight=9;\n    server localhost:8081 weight=1;\n}\n```\n\n那么10次一般只会有1次会访问到8081，而有9次会访问到8080\n\n#### ip_hash\n\n上面的2种方式都有一个问题，那就是下一个请求来的时候请求可能分发到另外一个服务器，当我们的程序不是无状态的时候（采用了session保存数据），这时候就有一个很大的很问题了，比如把登录信息保存到了session中，那么跳转到另外一台服务器的时候就需要重新登录了，所以很多时候我们需要一个客户只访问一个服务器，那么就需要用iphash了，iphash的每个请求按访问ip的hash结果分配，这样每个访客固定访问一个后端服务器，可以解决session的问题。\n\n```nginx\nupstream test {\n    ip_hash;\n    server localhost:8080;\n    server localhost:8081;\n}\n```\n\n#### fair\n\n这是个第三方模块，按后端服务器的响应时间来分配请求，响应时间短的优先分配。\n\n```nginx\nupstream backend {\n    fair;\n    server localhost:8080;\n    server localhost:8081;\n}\n```\n\n#### url_hash\n\n这是个第三方模块，按访问url的hash结果来分配请求，使每个url定向到同一个后端服务器，后端服务器为缓存时比较有效。 在upstream中加入hash语句，server语句中不能写入weight等其他的参数，hash_method是使用的hash算法\n\n```nginx\nupstream backend {\n    hash $request_uri;\n    hash_method crc32;\n    server localhost:8080;\n    server localhost:8081;\n}\n```\n\n以上5种负载均衡各自适用不同情况下使用，所以可以根据实际情况选择使用哪种策略模式，不过fair和url_hash需要安装第三方模块才能使用\n\n**server指令可选参数：**\n\n1. weight：设置一个服务器的访问权重，数值越高，收到的请求也越多；\n2. fail_timeout：在这个指定的时间内服务器必须提供响应，如果在这个时间内没有收到响应，那么服务器将会被标记为down状态；\n3. max_fails：设置在fail_timeout时间之内尝试对一个服务器连接的最大次数，如果超过这个次数，那么服务器将会被标记为down;\n4. down：标记一个服务器不再接受任何请求；\n5. backup：一旦其他服务器宕机，那么有该标记的机器将会接收请求。\n\n**keepalive指令：**\n\nNginx服务器将会为每一个worker进行保持同上游服务器的连接。\n\n### 屏蔽ip\n\n在nginx的配置文件`nginx.conf`中加入如下配置，可以放到http, server, location, limit_except语句块，需要注意相对路径，本例当中`nginx.conf`，`blocksip.conf`在同一个目录中。\n\n```nginx\ninclude blockip.conf;\n```\n\n在blockip.conf里面输入内容，如：\n\n```nginx\ndeny 165.91.122.67;\n\ndeny IP;   # 屏蔽单个ip访问\nallow IP;  # 允许单个ip访问\ndeny all;  # 屏蔽所有ip访问\nallow all; # 允许所有ip访问\ndeny 123.0.0.0/8   # 屏蔽整个段即从123.0.0.1到123.255.255.254访问的命令\ndeny 124.45.0.0/16 # 屏蔽IP段即从123.45.0.1到123.45.255.254访问的命令\ndeny 123.45.6.0/24 # 屏蔽IP段即从123.45.6.1到123.45.6.254访问的命令\n\n# 如果你想实现这样的应用，除了几个IP外，其他全部拒绝\nallow 1.1.1.1; \nallow 1.1.1.2;\ndeny all; \n```\n\n## 第三方模块安装方法\n\n```\n./configure --prefix=/你的安装目录  --add-module=/第三方模块目录\n```\n\n## 重定向\n\n- `permanent` 永久性重定向。请求日志中的状态码为301\n- `redirect` 临时重定向。请求日志中的状态码为302\n\n### 重定向整个网站\n\n```nginx\nserver {\n    server_name old-site.com\n    return 301 $scheme://new-site.com$request_uri;\n}\n```\n\n### 重定向单页\n\n```nginx\nserver {\n    location = /oldpage.html {\n        return 301 http://example.org/newpage.html;\n    }\n}\n```\n\n### 重定向整个子路径\n\n```nginx\nlocation /old-site {\n    rewrite ^/old-site/(.*) http://example.org/new-site/$1 permanent;\n}\n```\n\n## 性能\n\n### 内容缓存\n\n允许浏览器基本上永久地缓存静态内容。 Nginx将为您设置Expires和Cache-Control头信息。\n\n```nginx\nlocation /static {\n    root /data;\n    expires max;\n}\n```\n\n如果要求浏览器永远不会缓存响应（例如用于跟踪请求），请使用-1。\n\n```nginx\nlocation = /empty.gif {\n    empty_gif;\n    expires -1;\n}\n```\n\n### Gzip压缩\n\n```nginx\ngzip  on;\ngzip_buffers 16 8k;\ngzip_comp_level 6;\ngzip_http_version 1.1;\ngzip_min_length 256;\ngzip_proxied any;\ngzip_vary on;\ngzip_types\n    text/xml application/xml application/atom+xml application/rss+xml application/xhtml+xml image/svg+xml\n    text/javascript application/javascript application/x-javascript\n    text/x-json application/json application/x-web-app-manifest+json\n    text/css text/plain text/x-component\n    font/opentype application/x-font-ttf application/vnd.ms-fontobject\n    image/x-icon;\ngzip_disable  \"msie6\";\n```\n\n### 打开文件缓存\n\n```nginx\nopen_file_cache max=1000 inactive=20s;\nopen_file_cache_valid 30s;\nopen_file_cache_min_uses 2;\nopen_file_cache_errors on;\n```\n\n### SSL缓存\n\n```nginx\nssl_session_cache shared:SSL:10m;\nssl_session_timeout 10m;\n```\n\n### 上游Keepalive\n\n```nginx\nupstream backend {\n    server 127.0.0.1:8080;\n    keepalive 32;\n}\nserver {\n    ...\n    location /api/ {\n        proxy_pass http://backend;\n        proxy_http_version 1.1;\n        proxy_set_header Connection \"\";\n    }\n}\n```\n\n### 监控\n\n使用`ngxtop`实时解析nginx访问日志，并且将处理结果输出到终端，功能类似于系统命令top。所有示例都读取nginx配置文件的访问日志位置和格式。如果要指定访问日志文件和/或日志格式，请使用-f和-a选项。\n\n注意：在nginx配置中`/usr/local/nginx/conf/nginx.conf`日志文件必须是绝对路径。\n\n```bash\n# 安装 ngxtop\npip install ngxtop\n\n# 实时状态\nngxtop\n# 状态为404的前10个请求的路径：\nngxtop top request_path --filter 'status == 404'\n\n# 发送总字节数最多的前10个请求\nngxtop --order-by 'avg(bytes_sent) * count'\n\n# 排名前十位的IP，例如，谁攻击你最多\nngxtop --group-by remote_addr\n\n# 打印具有4xx或5xx状态的请求，以及status和http referer\nngxtop -i 'status \u003e= 400' print request status http_referer\n\n# 由200个请求路径响应发送的平均正文字节以'foo'开始：\nngxtop avg bytes_sent --filter 'status == 200 and request_path.startswith(\"foo\")'\n\n# 使用“common”日志格式从远程机器分析apache访问日志\nssh remote tail -f /var/log/apache2/access.log | ngxtop -f common\n```\n\n## 常见使用场景\n\n### 跨域问题\n\n在工作中，有时候会遇到一些接口不支持跨域，这时候可以简单的添加add_headers来支持cors跨域。配置如下：\n\n```nginx\nserver {\n  listen 80;\n  server_name api.xxx.com;\n    \n  add_header 'Access-Control-Allow-Origin' '*';\n  add_header 'Access-Control-Allow-Credentials' 'true';\n  add_header 'Access-Control-Allow-Methods' 'GET,POST,HEAD';\n\n  location / {\n    proxy_pass http://127.0.0.1:3000;\n    proxy_set_header X-Real-IP $remote_addr;\n    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;\n    proxy_set_header Host  $http_host;    \n  } \n}\n```\n\n上面更改头信息，还有一种，使用 [rewrite](http://nginx.org/en/docs/http/ngx_http_rewrite_module.html) 指令重定向URI来解决跨域问题。\n\n```nginx\nupstream test {\n  server 127.0.0.1:8080;\n  server localhost:8081;\n}\nserver {\n  listen 80;\n  server_name api.xxx.com;\n  location / { \n    root  html;                   #去请求../html文件夹里的文件\n    index  index.html index.htm;  #首页响应地址\n  }\n  # 用于拦截请求，匹配任何以 /api/开头的地址，\n  # 匹配符合以后，停止往下搜索正则。\n  location ^~/api/{ \n    # 代表重写拦截进来的请求，并且只能对域名后边的除去传递的参数外的字符串起作用，\n    # 例如www.a.com/proxy/api/msg?meth=1\u0026par=2重写，只对/proxy/api/msg重写。\n    # rewrite后面的参数是一个简单的正则 ^/api/(.*)$，\n    # $1代表正则中的第一个()，$2代表第二个()的值，以此类推。\n    rewrite ^/api/(.*)$ /$1 break;\n    \n    # 把请求代理到其他主机 \n    # 其中 http://www.b.com/ 写法和 http://www.b.com写法的区别如下\n    # 如果你的请求地址是他 http://server/html/test.jsp\n    # 配置一： http://www.b.com/ 后面有“/” \n    #         将反向代理成 http://www.b.com/html/test.jsp 访问\n    # 配置一： http://www.b.com 后面没有有“/” \n    #         将反向代理成 http://www.b.com/test.jsp 访问\n    proxy_pass http://test;\n\n    # 如果 proxy_pass  URL 是 http://a.xx.com/platform/ 这种情况\n    # proxy_cookie_path应该设置成 /platform/ / (注意两个斜杠之间有空格)。\n    proxy_cookie_path /platfrom/ /;\n\n    # http://nginx.org/en/docs/http/ngx_http_proxy_module.html#proxy_pass_header\n    # 设置 Cookie 头通过\n    proxy_pass_header Set-Cookie;\n  } \n}\n```\n\n### 跳转到带 www 的域上面\n\n```nginx\nserver {\n    listen 80;\n    # 配置正常的带www的域名\n    server_name www.wangchujiang.com;\n    root /home/www/wabg/download;\n    location / {\n        try_files $uri $uri/ /index.html =404;\n    }\n}\nserver {\n    # 这个要放到下面，\n    # 将不带www的 wangchujiang.com 永久性重定向到  https://www.wangchujiang.com\n    server_name wangchujiang.com;\n    rewrite ^(.*) https://www.wangchujiang.com$1 permanent;\n}\n```\n\n### 代理转发\n\n```nginx\nupstream server-api{\n    # api 代理服务地址\n    server 127.0.0.1:3110;    \n}\nupstream server-resource{\n    # 静态资源 代理服务地址\n    server 127.0.0.1:3120;\n}\nserver {\n    listen       3111;\n    server_name  localhost;      # 这里指定域名\n    root /home/www/server-statics;\n    # 匹配 api 路由的反向代理到API服务\n    location ^~/api/ {\n        rewrite ^/(.*)$ /$1 break;\n        proxy_pass http://server-api;\n    }\n    # 假设这里验证码也在API服务中\n    location ^~/captcha {\n        rewrite ^/(.*)$ /$1 break;\n        proxy_pass http://server-api;\n    }\n    # 假设你的图片资源全部在另外一个服务上面\n    location ^~/img/ {\n        rewrite ^/(.*)$ /$1 break;\n        proxy_pass http://server-resource;\n    }\n    # 路由在前端，后端没有真实路由，在路由不存在的 404状态的页面返回 /index.html\n    # 这个方式使用场景，你在写React或者Vue项目的时候，没有真实路由\n    location / {\n        try_files $uri $uri/ /index.html =404;\n        #                               ^ 空格很重要\n    }\n}\n```\n\n### 监控状态信息\n\n通过 `nginx -V` 来查看是否有 `with-http_stub_status_module` 该模块。\n\n\u003e `nginx -V` 这里 `V` 是大写的，如果是小写的 `v` 即 `nginx -v`，则不会出现有哪些模块，只会出现 `nginx` 的版本\n\n```nginx\nlocation /nginx_status {\n    stub_status on;\n    access_log off;\n}\n```\n\n通过 http://127.0.0.1/nginx_status 访问出现下面结果。\n\n```bash\nActive connections: 3\nserver accepts handled requests\n 7 7 5 \nReading: 0 Writing: 1 Waiting: 2 \n```\n\n1. 主动连接(第 1 行)\n\n当前与http建立的连接数，包括等待的客户端连接：3\n\n2. 服务器接受处理的请求(第 2~3 行)\n\n接受的客户端连接总数目：7  \n处理的客户端连接总数目：7  \n客户端总的请求数目：5  \n\n3. 读取其它信(第 4 行)\n\n当前，nginx读请求连接  \n当前，nginx写响应返回给客户端  \n目前有多少空闲客户端请求连接  \n\n### 代理转发连接替换\n\n```nginx\nlocation ^~/api/upload {\n    rewrite ^/(.*)$ /wfs/v1/upload break;\n    proxy_pass http://wfs-api;\n}\n```\n\n### SSL 配置\n\n超文本传输安全协议（缩写：HTTPS，英语：Hypertext Transfer Protocol Secure）是超文本传输协议和SSL/TLS的组合，用以提供加密通讯及对网络服务器身份的鉴定。HTTPS连接经常被用于万维网上的交易支付和企业信息系统中敏感信息的传输。HTTPS不应与在RFC 2660中定义的安全超文本传输协议（S-HTTP）相混。HTTPS 目前已经是所有注重隐私和安全的网站的首选，随着技术的不断发展，HTTPS 网站已不再是大型网站的专利，所有普通的个人站长和博客均可以自己动手搭建一个安全的加密的网站。\n\n\n创建SSL证书，如果你购买的证书，就可以直接下载\n\n```bash\nsudo mkdir /etc/nginx/ssl\n# 创建了有效期100年，加密强度为RSA2048的SSL密钥key和X509证书文件。\nsudo openssl req -x509 -nodes -days 36500 -newkey rsa:2048 -keyout /etc/nginx/ssl/nginx.key -out /etc/nginx/ssl/nginx.crt\n# 上面命令，会有下面需要填写内容\nCountry Name (2 letter code) [AU]:US\nState or Province Name (full name) [Some-State]:New York\nLocality Name (eg, city) []:New York City\nOrganization Name (eg, company) [Internet Widgits Pty Ltd]:Bouncy Castles, Inc.\nOrganizational Unit Name (eg, section) []:Ministry of Water Slides\nCommon Name (e.g. server FQDN or YOUR name) []:your_domain.com\nEmail Address []:admin@your_domain.com\n```\n\n创建自签证书\n\n```bash\n首先，创建证书和私钥的目录\n# mkdir -p /etc/nginx/cert\n# cd /etc/nginx/cert\n创建服务器私钥，命令会让你输入一个口令：\n# openssl genrsa -des3 -out nginx.key 2048\n创建签名请求的证书（CSR）：\n# openssl req -new -key nginx.key -out nginx.csr\n在加载SSL支持的Nginx并使用上述私钥时除去必须的口令：\n# cp nginx.key nginx.key.org\n# openssl rsa -in nginx.key.org -out nginx.key\n最后标记证书使用上述私钥和CSR：\n# openssl x509 -req -days 365 -in nginx.csr -signkey nginx.key -out nginx.crt\n```\n\n查看目前nginx编译选项\n\n```\nsbin/nginx -V\n```\n\n输出下面内容\n\n```\nnginx version: nginx/1.7.8\nbuilt by gcc 4.4.7 20120313 (Red Hat 4.4.7-4) (GCC)\nTLS SNI support enabled\nconfigure arguments: --prefix=/usr/local/nginx-1.7.8 --with-http_ssl_module --with-http_spdy_module --with-http_stub_status_module --with-pcre\n```\n\n如果依赖的模块不存在，可以进入安装目录，输入下面命令重新编译安装。\n\n```bash\n./configure --prefix=/usr/local/nginx --with-http_stub_status_module --with-http_ssl_module\n```\n\n运行完成之后还需要`make` (不用make install)\n\n```bash\n# 备份nginx的二进制文件\ncp -rf /usr/local/nginx/sbin/nginx　 /usr/local/nginx/sbin/nginx.bak\n# 覆盖nginx的二进制文件\ncp -rf objs/nginx   /usr/local/nginx/sbin/\n```\n\nHTTPS server\n\n```nginx\nserver {\n    listen       443 ssl;\n    server_name  localhost;\n\n    ssl_certificate /etc/nginx/ssl/nginx.crt;\n    ssl_certificate_key /etc/nginx/ssl/nginx.key;\n    # 禁止在header中出现服务器版本，防止黑客利用版本漏洞攻击\n    server_tokens off;\n    # 设置ssl/tls会话缓存的类型和大小。如果设置了这个参数一般是shared，buildin可能会参数内存碎片，默认是none，和off差不多，停用缓存。如shared:SSL:10m表示我所有的nginx工作进程共享ssl会话缓存，官网介绍说1M可以存放约4000个sessions。 \n    ssl_session_cache    shared:SSL:1m; \n\n    # 客户端可以重用会话缓存中ssl参数的过期时间，内网系统默认5分钟太短了，可以设成30m即30分钟甚至4h。\n    ssl_session_timeout  5m; \n\n    # 选择加密套件，不同的浏览器所支持的套件（和顺序）可能会不同。\n    # 这里指定的是OpenSSL库能够识别的写法，你可以通过 openssl -v cipher 'RC4:HIGH:!aNULL:!MD5'（后面是你所指定的套件加密算法） 来看所支持算法。\n    ssl_ciphers  HIGH:!aNULL:!MD5;\n\n    # 设置协商加密算法时，优先使用我们服务端的加密套件，而不是客户端浏览器的加密套件。\n    ssl_prefer_server_ciphers  on;\n\n    location / {\n        root   html;\n        index  index.html index.htm;\n    }\n}\n```\n\n### 强制将http重定向到https\n\n```nginx\nserver {\n    listen       80;\n    server_name  example.com;\n    rewrite ^ https://$http_host$request_uri? permanent;    # 强制将http重定向到https\n    # 在错误页面和“服务器”响应头字段中启用或禁用发射nginx版本。 防止黑客利用版本漏洞攻击\n    server_tokens off;\n}\n```\n\n### 两个虚拟主机\n\n纯静态-html 支持\n\n```nginx\nhttp {\n    server {\n        listen          80;\n        server_name     www.domain1.com;\n        access_log      logs/domain1.access.log main;\n        location / {\n            index index.html;\n            root  /var/www/domain1.com/htdocs;\n        }\n    }\n    server {\n        listen          80;\n        server_name     www.domain2.com;\n        access_log      logs/domain2.access.log main;\n        location / {\n            index index.html;\n            root  /var/www/domain2.com/htdocs;\n        }\n    }\n}\n```\n\n### 虚拟主机标准配置\n\n```nginx\nhttp {\n  server {\n    listen          80 default;\n    server_name     _ *;\n    access_log      logs/default.access.log main;\n    location / {\n       index index.html;\n       root  /var/www/default/htdocs;\n    }\n  }\n}\n```\n\n### 爬虫过滤\n\n根据 `User-Agent` 过滤请求，通过一个简单的正则表达式，就可以过滤不符合要求的爬虫请求(初级爬虫)。\n\n\u003e `~*` 表示不区分大小写的正则匹配\n\n```nginx\nlocation / {\n    if ($http_user_agent ~* \"python|curl|java|wget|httpclient|okhttp\") {\n        return 503;\n    }\n    # 正常处理\n    # ...\n}\n```\n\n### 防盗链\n\n```nginx\nlocation ~* \\.(gif|jpg|png|swf|flv)$ {\n   root html\n   valid_referers none blocked *.nginxcn.com;\n   if ($invalid_referer) {\n     rewrite ^/ www.nginx.cn\n     #return 404;\n   }\n}\n```\n\n### 虚拟目录配置\n\nalias指定的目录是准确的，root是指定目录的上级目录，并且该上级目录要含有location指定名称的同名目录。\n\n```nginx\nlocation /img/ {\n    alias /var/www/image/;\n}\n# 访问/img/目录里面的文件时，ningx会自动去/var/www/image/目录找文件\nlocation /img/ {\n    root /var/www/image;\n}\n# 访问/img/目录下的文件时，nginx会去/var/www/image/img/目录下找文件。]\n```\n\n### 防盗图配置\n\n```nginx\nlocation ~ \\/public\\/(css|js|img)\\/.*\\.(js|css|gif|jpg|jpeg|png|bmp|swf) {\n    valid_referers none blocked *.jslite.io;\n    if ($invalid_referer) {\n        rewrite ^/  http://wangchujiang.com/piratesp.png;\n    }\n}\n```\n\n### 屏蔽.git等文件\n\n```nginx\nlocation ~ (.git|.gitattributes|.gitignore|.svn) {\n    deny all;\n}\n```\n\n### 域名路径加不加需要都能正常访问\n\n```bash\nhttp://wangchujiang.com/api/index.php?a=1\u0026name=wcj\n                                  ^ 有后缀\n\nhttp://wangchujiang.com/api/index?a=1\u0026name=wcj\n                                 ^ 没有后缀\n```\n\nnginx rewrite规则如下：\n\n```nginx\nrewrite ^/(.*)/$ /index.php?/$1 permanent;\nif (!-d $request_filename){\n        set $rule_1 1$rule_1;\n}\nif (!-f $request_filename){\n        set $rule_1 2$rule_1;\n}\nif ($rule_1 = \"21\"){\n        rewrite ^/ /index.php last;\n}\n```\n\n### cockpit\n\nhttps://github.com/cockpit-project/cockpit\n\n```nginx\nserver{\n    listen 80;\n    server_name cockpit.xxxxxxx.com;\n    return 301 https://$server_name$request_uri;\n}\n \nserver {\n    listen 443 ssl;\n    server_name cockpit.xxxxxxx.com;\n \n    #ssl on;\n    ssl_certificate /etc/nginx/cert/cockpit.xxxxxxx.com.pem;\n    ssl_certificate_key /etc/nginx/cert/cockpit.xxxxxxx.com.key;\n \n    location / {\n        root /;\n        index index.html;\n        proxy_redirect off;\n        proxy_pass http://websocket;\n        proxy_http_version 1.1;\n        proxy_set_header Upgrade $http_upgrade;\n        proxy_set_header Connection \"upgrade\";\n        proxy_set_header Host $http_host;\n    }\n}\n```\n\n这时输入域名，能看到登录页面，但登录后，显示不出内容，页面全白。这里要对 `cockpit.conf` 进行设置修改。\n\n```bash\nsudo vim /etc/cockpit/cockpit.conf\n```\n\n参照如下配置修改，注意域名替换为 `your_domain_host`：\n\n```toml\n[WebService]\nOrigins = https://cockpit.xxxxxxx.com https://127.0.0.1:9090\nProtocolHeader = X-Forwarded-Proto\nAllowUnencrypted = true\n```\n\n## 错误问题\n\n```bash\nThe plain HTTP request was sent to HTTPS port\n```\n\n解决办法，`fastcgi_param HTTPS $https if_not_empty` 添加这条规则，\n\n```nginx\nserver {\n    listen 443 ssl; # 注意这条规则\n    server_name  my.domain.com;\n    \n    fastcgi_param HTTPS $https if_not_empty;\n    fastcgi_param HTTPS on;\n\n    ssl_certificate /etc/ssl/certs/your.pem;\n    ssl_certificate_key /etc/ssl/private/your.key;\n\n    location / {\n        # Your config here...\n    }\n}\n```\n\n## Nginx 模块\n\n- [Nginx Office Hours](https://gitlab.com/rbdr/ngx_http_office_hours_filter_module) 一个 nginx 模块，允许您仅在办公时间内提供访问访问网站。\n\n## 精品文章参考\n\n- [负载均衡原理的解析](https://my.oschina.net/u/3341316/blog/877206)\n- [Nginx泛域名解析，实现多个二级域名 ](http://blog.githuber.cn/posts/73)\n- [深入 NGINX: 我们如何设计性能和扩展](https://www.nginx.com/blog/inside-nginx-how-we-designed-for-performance-scale/)\n- [Inside NGINX: How We Designed for Performance \u0026 Scale](https://www.nginx.com/blog/inside-nginx-how-we-designed-for-performance-scale/)\n- [Nginx开发从入门到精通](http://tengine.taobao.org/book/index.html)\n- [Nginx的优化与防盗链](http://os.51cto.com/art/201703/535326.htm#topx)\n- [实战开发一个Nginx扩展 (Nginx Module)](https://segmentfault.com/a/1190000009769143)\n- [Nginx+Keepalived(双机热备)搭建高可用负载均衡环境(HA)](https://my.oschina.net/xshuai/blog/917097)\n- [Nginx 平滑升级](http://www.huxd.org/articles/2017/07/24/1500890692329.html)\n- [Nginx最新模块—ngx_http_mirror_module分析可以做版本发布前的预先验证，进行流量放大后的压测等等](https://mp.weixin.qq.com/s?__biz=MzIxNzg5ODE0OA==\u0026mid=2247483708\u0026idx=1\u0026sn=90b0b1dccd9c337922a0588245277666\u0026chksm=97f38cf7a08405e1928e0b46d923d630e529e7db8ac7ca2a91310a075986f8bcb2cee5b4953d#rd)\n\n## Contributors\n\nAs always, thanks to our amazing contributors!\n\n\u003ca href=\"https://github.com/jaywcjlove/nginx-tutorial/graphs/contributors\"\u003e\n  \u003cimg src=\"https://jaywcjlove.github.io/nginx-tutorial/CONTRIBUTORS.svg\" /\u003e\n\u003c/a\u003e\n\nMade with [action-contributors](https://github.com/jaywcjlove/github-action-contributors).\n\n## License\n\nLicensed under the MIT License.\n","funding_links":["https://ko-fi.com/jaywcjlove","https://buymeacoffee.com/jaywcjlove","https://www.paypal.me/kennyiseeyou","https://jaywcjlove.github.io/#/sponsor"],"categories":["miscellaneous","Uncategorized","Others","Web"],"sub_categories":["Uncategorized","PHP"],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fjaywcjlove%2Fnginx-tutorial","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fjaywcjlove%2Fnginx-tutorial","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fjaywcjlove%2Fnginx-tutorial/lists"}