Nginx 配置

在了解具体的Nginx配置项之前我们需要对于Nginx配置文件的构成有所概念,一般来说,Nginx配置文件会由如下几个部分构成:

# 全局块
...
# events块
events {
...
}
# http块
http
{
# http全局块
...
# 虚拟主机server块
server
{
# server全局块
...
# location块
location [PATTERN]
{
...
}
location [PATTERN]
{
...
}
}
server
{
...
}
# http全局块
...
}

在上述配置中我们可以看出,Nginx配置文件由以下几个部分构成:

  • 全局块:配置影响nginx全局的指令。一般有运行nginx服务器的用户组,nginx进程pid存放路径,日志存放路径,配置文件引入,允许生成worker process数等。

  • events块:配置影响nginx服务器或与用户的网络连接。有每个进程的最大连接数,选取哪种事件驱动模型处理连接请求,是否允许同时接受多个网路连接,开启多个网络连接序列化等。

  • http块:可以嵌套多个server,配置代理,缓存,日志定义等绝大多数功能和第三方模块的配置。如文件引入,mime-type定义,日志自定义,是否使用sendfile传输文件,连接超时时间,单连接请求数等。

  • server块:配置虚拟主机的相关参数,一个http中可以有多个server。

  • location块:配置请求的路由,以及各种页面的处理情况。

########### 每个指令必须有分号结束。#################
#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 4545; #监听端口
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进行静态内容服务,Nginx的静态内容分发能力还是非常强大的。

http {
server {
listen 80;
server_name www.domain1.com;
access_log logs/domain1.access.log main;
location / {
index index.html;
root /var/www/domain1.com/htdocs;
}
}
server {
listen 80;
server_name www.domain2.com;
access_log logs/domain2.access.log main;
location / {
index index.html;
root /var/www/domain2.com/htdocs;
}
}
}

虚拟主机配置详解

主机与端口

listen 127.0.0.1:8000;
listen *:8000;
listen localhost:8000;
# IPV6
listen [::]:8000;
# other params
listen 443 default_serer ssl;
listen 127.0.0.1 default_server accept_filter=dataready backlog=1024

服务域名

# 支持多域名配置
server_name www.barretlee.com barretlee.com;
# 支持泛域名解析
server_name *.barretlee.com;
# 支持对于域名的正则匹配
server_name ~^\.barret\.com$;

URI匹配

location = / {
# 完全匹配 =
# 大小写敏感 ~
# 忽略大小写 ~*
}
location ^~ /images/ {
# 前半部分匹配 ^~
# 可以使用正则,如:
# location ~* \.(gif|jpg|png)$ { }
}
location / {
# 如果以上都未匹配,会进入这里
}

文件路径配置

根目录

location / {
root /home/barret/test/;
}

别名

location /blog {
alias /home/barret/www/blog/;
}
location ~ ^/blog/(\d+)/([\w-]+)$ {
# /blog/20141202/article-name
# -> /blog/20141202-article-name.md
alias /home/barret/www/blog/$1-$2.md;
}

首页

index /html/index.html /php/index.php;

重定向页面

error_page    404         /404.html;
error_page 502 503 /50x.html;
error_page 404 =200 /1x1.gif;
location / {
error_page 404 @fallback;
}
location @fallback {
# 将请求反向代理到上游服务器处理
proxy_pass http://localhost:9000;
}

try_files

try_files $uri $uri.html $uri/index.html @other;
location @other {
# 尝试寻找匹配 uri 的文件,失败了就会转到上游处理
proxy_pass http://localhost:9000;
}
location / {
# 尝试寻找匹配 uri 的文件,没找到直接返回 502
try_files $uri $uri.html =502;
}

缓存配置

Expire:过期时间

在Nginx中可以配置缓存的过期时间:

location ~* \.(?:ico|css|js|gif|jpe?g|png)$ {
expires 30d;
add_header Vary Accept-Encoding;
access_log off;
}

我们也可以添加更复杂的配置项:

location ~* ^.+\.(?:css|cur|js|jpe?g|gif|htc|ico|png|html|xml|otf|ttf|eot|woff|svg)$ {

        access_log off;
expires 30d;
## No need to bleed constant updates. Send the all shebang in one
## fell swoop.
tcp_nodelay off;
## Set the OS file cache.
open_file_cache max=3000 inactive=120s;
open_file_cache_valid 45s;
open_file_cache_min_uses 2;
open_file_cache_errors off;
}

反向代理

events{

}
http{
upstream ggzy {
server 127.0.0.1:1398 weight=3;
server 127.0.0.1:1399;
}
# 80端口配置,可配置多个Virtual Host
server {
listen 80;
index index index.htm index.py index.html; server_name app.truelore.cn; location / {
proxy_pass_header Server;
proxy_set_header Host $http_host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Scheme $scheme;
proxy_pass http//ggzy;
}
}
}

NodeJS Application

const http = require('http');
http.createServer((req, res) => {
res.end('hello world');
}).listen(9000);

任何请求过来都返回 hello world,简版的 Nginx 配置如下,

events {
# 这里可不写东西
use epoll;
}
http {
server {
listen 127.0.0.1:8888;
# 如果请求路径跟文件路径按照如下方式匹配找到了,直接返回
try_files $uri $uri/index.html;
location ~* ^/(js|css|image|font)/$ {
# 静态资源都在 static 文件夹下
root /home/barret/www/static/;
}
location /app {
# Node.js 在 9000 开了一个监听端口
proxy_pass http://127.0.0.1:9000;
}
# 上面处理出错或者未找到的,返回对应状态码文件
error_page 404 /404.html;
error_page 502 503 504 /50x.html;
}
}

首先 try_files,尝试直接匹配文件;没找到就匹配静态资源;还没找到就交给 Node 处理;否则就返回 4xx/5xx 的状态码。

Upstream Cache

http {
,,,,,
proxy_cache_path /var/cache/nginx/cache levels=1:2 keys_zone=imgcache:100m inactive=1d max_size=10g;
server {
........
location ~* ^.+\.(js|ico|gif|jpg|jpeg|png|html|htm)$ {
log_not_found off;
access_log off;
expires 7d;
proxy_pass http://img.example.com ;
proxy_cache imgcache;
proxy_cache_valid 200 302 1d;
proxy_cache_valid 404 10m;
proxy_cache_valid any 1h;
proxy_cache_use_stale error timeout invalid_header updating http_500 http_502 http_503 http_504;
}
}
}

HTTPS

Let's Encrypt 证书申请

Let's Encrypt 为我们提供了非常方便的命令行工具 certbot,笔者是在Ubuntu
16.04的机器上进行配置,因此只要执行如下命令即可:

# 安装letsencrypt命令行

$ sudo apt-get install letsencrypt
# 独立的为example.com与www.example.com申请证书
$ letsencrypt certonly --standalone -d example.com -d www.example.com
# 自动执行证书刷新操作
$ letsencrypt renew --dry-run --agree-tos

基本HTTPS配置

基本的HTTPS支持配置如下:

server {
listen 192.168.1.11:443; #ssl端口
server_name test.com;
#为一个server{......}开启ssl支持
ssl on;
#指定PEM格式的证书文件
ssl_certificate /etc/nginx/test.pem;
#指定PEM格式的私钥文件
ssl_certificate_key /etc/nginx/test.key;
}

在真实的生产环境中,我们的配置如下:

server {
# 如果需要spdy也可以加上,lnmp1.2及其后版本都默认支持spdy,lnmp1.3 nginx 1.9.5以上版本默认支持http2
listen 443 ssl;
# 这里是你的域名
server_name www.vpser.net;
index index.html index.htm index.php default.html default.htm default.php;
# 网站目录
root /home/wwwroot/www.vpser.net;
# 前面生成的证书,改一下里面的域名就行
ssl_certificate /etc/letsencrypt/live/www.vpser.net/fullchain.pem;
# 前面生成的密钥,改一下里面的域名就行
ssl_certificate_key /etc/letsencrypt/live/www.vpser.net/privkey.pem;
ssl_ciphers "EECDH+CHACHA20:EECDH+CHACHA20-draft:EECDH+AES128:RSA+AES128:EECDH+AES256:RSA+AES256:EECDH+3DES:RSA+3DES:!MD5";
ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
ssl_prefer_server_ciphers on;
ssl_session_cache shared:SSL:10m; #这个是伪静态根据自己的需求改成其他或删除
include wordpress.conf; #error_page 404 /404.html; location ~ [^/]\.php(/|$)
{
# comment try_files $uri =404; to enable pathinfo
try_files $uri =404;
fastcgi_pass unix:/tmp/php-cgi.sock;
fastcgi_index index.php;
# lnmp 1.0及之前版本替换为include fcgi.conf;
include fastcgi.conf;
#include pathinfo.conf;
} location ~ .*\.(gif|jpg|jpeg|png|bmp|swf)$
{
expires 30d;
} location ~ .*\.(js|css)?$
{
expires 12h;
} access_log off;
}

强制HTTP转到HTTPS

Nginx Rewrite

server {
listen 192.168.1.111:80;
server_name test.com;
rewrite ^(.*)$ https://$host$1 permanent;
}

Nginx 497错误码

利用error_page命令将497状态码的链接重定向到 https://
test.com
这个域名上

server {
listen 192.168.1.11:443; #ssl端口
listen 192.168.1.11:80; #用户习惯用http访问,加上80,后面通过497状态码让它自动跳到443端口
server_name test.com;
#为一个server{......}开启ssl支持
ssl on;
#指定PEM格式的证书文件
ssl_certificate /etc/nginx/test.pem;
#指定PEM格式的私钥文件
ssl_certificate_key /etc/nginx/test.key; #让http请求重定向到https请求
error_page 497 https://$host$uri?$args;
}

Meta刷新,前端跳转

在HTTP正常返回的页面中添加meta属性:

<html>
<meta http-equiv="refresh" content="0;url=https://test.com/">
</html>
server {
listen 192.168.1.11:80;
server_name test.com; location / {
#index.html放在虚拟主机监听的根目录下
root /srv/www/http.test.com/;
}
#将404的页面重定向到https的首页
error_page 404 https://test.com/;
}

Nginx学习总结(5)——Nginx基本配置备忘的更多相关文章

  1. nginx 学习笔记(2) nginx新手入门

    这篇手册简单介绍了nginx,并提供了一些可以操作的简单的工作.前提是nginx已经被安装到你的服务器上.如果没有安装,请阅读上篇:nginx 学习笔记(1) nginx安装.这篇手册主要内容:1. ...

  2. 生产服务器环境最小化安装后 Centos 6.5优化配置备忘

    生产服务器环境最小化安装后 Centos 6.5优化配置备忘 作者:Memory 发布于:2014-8-13 15:00 Wednesday 服务器 本文 centos 6.5 优化 的项有18处: ...

  3. 生产服务器环境最小化安装后Centos 6.5优化配置备忘

    生产服务器环境最小化安装后 Centos 6.5优化配置备忘 本文 centos 6.5 优化 的项有18处,列表如下: 1.centos6.5最小化安装后启动网卡 2.ifconfig查询IP进行S ...

  4. Manjaro启动项目及服务配置备忘

    Manjaro启动项目及服务配置备忘 =============== 系统服务GUI管理搜索 systemdgenie 并安装,类似Windows的服务管理. ================ 系统启 ...

  5. nginx配置备忘

    一.本地测试环境配置 upstream gongsibao{ server ; server ; #fair; } server { listen ; server_name ubuntu00.xus ...

  6. nginx 学习笔记(1) nginx安装

    1.nginx安装 根据操作系统的不同,nginx的安装方式也不相同. 1.1 对linux系统来说,nginx.org提供了nginx安装包.http://nginx.org/en/linux_pa ...

  7. nginx学习(三):nginx的进程模型

    概述 nginx 进程分为 master进程和work进程 1.打开配置文件查看,这里我修改为2 [root@xxx conf]# vim nginx.conf #user nobody; worke ...

  8. Nginx基本配置备忘

    原文:http://www.open-open.com/lib/view/open1482477873078.html Nginx 配置 在了解具体的Nginx配置项之前我们需要对于Nginx配置文件 ...

  9. Nginx学习之十一-Nginx启动框架处理流程

    Nginx启动过程流程图 下面首先给出Nginx启动过程的流程图: ngx_cycle_t结构体 Nginx的启动初始化在src/core/nginx.c的main函数中完成,当然main函数是整个N ...

随机推荐

  1. Codeforces Round #321 (Div. 2) A, B, C, D, E

    580A. Kefa and First Steps 题目链接: A. Kefa and First Steps 题意描述: 给出一个序列,求最长不降连续子序列多长? 解题思路: 水题,签到 代码: ...

  2. 递推DP HDOJ 5092 Seam Carving

    题目传送门 /* 题意:从上到下,找最短路径,并输出路径 DP:类似数塔问题,上一行的三个方向更新dp,路径输出是关键 */ #include <cstdio> #include < ...

  3. 123 Best Time to Buy and Sell Stock III 买卖股票的最佳时机 III

    假设你有一个数组,它的第 i 个元素是一支给定的股票在第 i 天的价格.设计一个算法来找到最大的利润.你最多可以完成两笔交易.注意:你不可同时参与多笔交易(你必须在再次购买前出售掉之前的股票).详见: ...

  4. python_11(网络编程)

    第1章 ucp协议 1.1 特性 1.2 缺陷 1.3 UDP协议实时通信 第2章 socket的更多方法 2.1 面向锁的套接字方法 2.1.1 blocking设置非阻塞 2.1.2 Blocki ...

  5. poj1862 Stripies

    思路: 简单贪心. 实现: #include <iostream> #include <cstdio> #include <algorithm> #include ...

  6. 安卓&IOS 手机添加O365 邮箱账户

    手机添加O365 邮件账户 一.Android手机添加O365邮件账户 1. 找到手机上“电子邮件” 2. 打开设置 3. 点击添加账户 4. 选择“Exchange” 5. 输入O365的邮箱账户和 ...

  7. Oracle 11g r2 Enterprise Manager (EM) 中文页面调整为英文页面

    Oracle 11g r2 Enterprise Manager (EM) 在中文语言环境下, 部分功能(如包含时间的查询数据库实例: orcl  >  指导中心  >  SQL 优化概要 ...

  8. chrome调试之Workspaces

    可通过workspaces来编辑本地文件 workspaces是Chrome DevTools的一个强大功能,这使DevTools变成了一个真正的IDE.Workspaces会将Sources选项卡中 ...

  9. 从源码中无法看出函数所在的js脚本的解决方法

    通过设置断点调试使js脚本自动出现

  10. H3C S5024P交换机互连实验

    第一次周二网络管理实验报告 交换机互联实验 实验接线图: 交换机全貌: 可以通过超级终端和telnet来配置交换机       控制电缆连交换机console口与计算机主机(只可以传送命令不可以通信, ...