Nginx 配置

发布时间: 更新时间: 总字数:2544 阅读时间:6m 作者: 分享 复制网址

Nginx 配置

配置说明

nginx.conf 配置文件:

#user  nobody;
worker_processes  1;    # worker 的数量

#error_log  logs/error.log;
error_log  logs/error.log;
#error_log  logs/error.log  notice;
#error_log  logs/error.log  info;

#pid        logs/nginx.pid;

events {    # 事件
    worker_connections  1024;    # 每个 worker 的最大连接数
}

http {
    include       mime.types;
    default_type  application/octet-stream;

    log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                     '$status $body_bytes_sent "$http_referer" '
                     '"$http_user_agent" "$http_x_forwarded_for"';

    access_log  logs/access.log  main;

    sendfile        on;
    #tcp_nopush     on;

    #keepalive_timeout  0;
    keepalive_timeout  65;

    gzip  on;

    # server {
        # listen       80;
        # server_name  localhost;

        #charset koi8-r;

        #access_log  logs/host.access.log  main;

        # location / {
        #     root   html;
        #     index  index.html index.htm;
        # }

        #error_page  404              /404.html;

        # redirect server error pages to the static page /50x.html
        #
        # error_page   500 502 503 504  /50x.html;
        # location = /50x.html {
        #     root   html;
        # }

        # proxy the PHP scripts to Apache listening on 127.0.0.1:80
        #
        #location ~ \.php$ {
        #    proxy_pass   http://127.0.0.1;
        #}

        # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
        #
        #location ~ \.php$ {
        #    root           html;
        #    fastcgi_pass   127.0.0.1:9000;
        #    fastcgi_index  index.php;
        #    fastcgi_param  SCRIPT_FILENAME  /scripts$fastcgi_script_name;
        #    include        fastcgi_params;
        #}

        # deny access to .htaccess files, if Apache's document root
        # concurs with nginx's one
        #
        #location ~ /\.ht {
        #    deny  all;
        #}
    # }

    include /etc/nginx/conf.d/*.conf;
}

说明:

  • 使用 # 注释
  • 单引号或双引号引用字符串,使用 \ 转移字符
  • 使用 ; 表示行配置结束
  • 指令 include 引用其它配置文件,支持使用通配符 *
  • 变量引用 $var
  • {} 引用配置块
    • http {} HTTP 块

内置预定义变量

  • $arg_PARAMETER GET请求中变量名PARAMETER参数的值
  • $args GET请求中的参数,例如 foo=123&bar=456; 这个变量只可以被修改
  • $binary_remote_addr 二进制码形式的客户端地址
  • $body_bytes_sent 传送页面的字节数
  • $content_length 请求头中的Content-length字段
  • $content_type 请求头中的Content-Type字段
  • $cookie_COOKIE cookie COOKIE的值
  • $document_root 当前请求在root指令中指定的值
  • $document_uri$uri 相同
  • $host 请求中的主机头(Host)字段,如果请求中的主机头不可用或者空,则为处理请求的server名称(处理请求的server的server_name指令的值)。值为小写,不包含端口
  • $hostname 机器名使用 gethostname 系统调用的值
  • $http_HEADER HTTP请求头中的内容,HEADER为HTTP请求中的内容转为小写,-变为_(破折号变为下划线),例如:$http_user_agent(Uaer-Agent的值)
  • $http_user_agent 客户端agent信息
  • $http_cookie 客户端cookie信息
  • $sent_http_HEADER HTTP响应头中的内容,HEADER为HTTP响应中的内容转为小写,-变为_,例如:$sent_http_cache_control, $sent_http_content_type
  • $is_args 如果$args设置,值为"?",否则为""
  • $limit_rate 这个变量可以限制连接速率
  • $nginx_version 当前运行的nginx版本号
  • $query_string$args 相同
  • $remote_addr 客户端的IP地址
  • $remote_port 客户端的端口
  • $remote_user 已经经过Auth Basic Module验证的用户名
  • $request_filename 当前连接请求的文件路径,由root或alias指令与URI请求生成
  • $request_body 请求的主要信息。在使用proxy_pass或fastcgi_pass指令的location中比较有意义
  • $request_body_file 客户端请求主体信息的临时文件名
  • $request_completion 如果请求成功,设为"OK";如果请求未完成或者不是一系列请求中最后一部分则设为空
  • $request_method 这个变量是客户端请求的动作,通常为GET或POST
  • $request_uri 这个变量等于包含一些客户端请求参数的原始URI,它无法修改,请查看$uri更改或重写URI,包含请求参数的原始URI,不包含主机名,如:/foo/bar.php?arg=baz
  • $scheme 所用的协议,比如http或者是https,比如 rewrite ^(.+)$ $scheme://example.com$1 redirect
  • $server_addr 服务器地址,在完成一次系统调用后可以确定这个值,如果要绕开系统调用,则必须在listen中指定地址并且使用bind参数
  • $server_name 服务器名称
  • $server_port 请求到达服务器的端口号
  • $server_protocol 请求使用的协议,通常是HTTP/1.0或HTTP/1.1
  • $uri 请求中的当前URI(不带请求参数,参数位于args),不同于浏览器传递的args,不同于浏览器传递的request_uri的值,它可以通过内部重定向,或者使用index指令进行修改。uri不包含主机名,如 /foo/bar.html

location

location Web 服务的 URI,对应 RESTful API,格式:

location [= | ~ | ~* ...] uri { ... }

说明:

  • = 表示精确匹配,优先级也是最高的
  • ^~ 表示uri以某个常规字符串开头,匹配 URI 的前半部分
  • ~ 表示区分大小写的正则匹配
  • ~* 表示不区分大小写的正则匹配
  • !~ 表示区分大小写不匹配的正则
  • !~* 表示不区分大小写不匹配的正则
  • / 通用匹配,任何请求都会匹配到

优先级:

= > ^~ > ~ / ~* / !~ / !~* > /

来源限制策略

  • [参考]http://nginx.org/en/docs/http/ngx_http_access_module.html
location / {
    deny  172.20.1.1;
    allow 172.21.0.0/16;
    deny  all;
}

proxy_pass

location /pass {
    proxy_set_header    Host            $host;  # 转发原始请求的 host 头部,即域名,域名在代理时透传到后端的服务器
    proxy_set_header    X-Real-IP       $remote_addr;  # 多次代理获取 IP
    proxy_set_header    X-Forwarded-For $proxy_add_x_forwarded_for;

    proxy_pass http://backend;      # 转发到 upstream
}

说明:

  • proxy_pass 转发 HTTP、HTTPS 服务
  • fastcgi_pass 转发 fastcgi
  • memcached_pass 转发 memcached

upstream

配置 server 指令的上游服务器域名或 IP 地址:

upstream backend {
    least_conn;                  # 负载均衡策略,包括:least_conn/hash/ip_hash,默认加权轮训(round robin)
    server 127.0.0.1:80;         # server 配置上游服务器
    server 172.20.0.1 weight=2;  # weight/backup/down/max_fails 服务器的状态
    server 172.20.0.2 backup;

    keepalive 60;
}

rewrite

  • rewrite 在 Nginx 中实现 URL 重写功能,nginx 编译时需要指定 ngx_http_rewrite_module,该指令通过正则表达式获取匹配服,并按照顺序依次对 URL 进行匹配和处理
  • 作用范围:server{},location{},if{}
  • 使用场景
    • 根据SEO或用户体验调整URL
    • 把动态 URL 地址伪装成静态地址
    • 让旧域名的访问跳转到新域名上
    • 根据特殊变量、目录、客户端的信息等进行URL跳转
  • 格式如下
rewrite regex replacement [flag];

说明:

  • rewrite URL重写的指令

  • regex 匹配 URI 的正则表达式

  • replacementregex 正则表达式匹配到的内容替换成 replacement

  • flag 标记支持如下值:

    • last 匹配后继续向下匹配新的规则
    • break 匹配后不再匹配后面的任何规则
    • redirect 返回302临时重定向,浏览器跳转新的URL地址
    • permanent 返回301永久重定向,浏览器跳转新的URL地址
  • 示例

rewrite ^/(.*) http://www.baidu.com/$1 permanent;

说明:

  • regex^/(.*) 匹配完整的域名和后面的路径地址
  • replacementhttp://www.baidu.com/1,其中 1 是取 regex 部分 (.*) 的内容,即若匹配成功后跳转到的URL
  • flagpermanent,代表永久重定向的含义

日志

格式:

    # 日志格式
    # log_format name format_str;
    log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                     '$status $body_bytes_sent "$http_referer" '
                     '"$http_user_agent" "$http_x_forwarded_for"';

    # 定义使用 8KB 的缓存,每秒刷新一次
    # access_log path [format [buffer=size] [flush=time]];
    access_log  logs/access.log  main  buffer=8k  flush=1s;

日志的分类:

  • access_log 记录 HTTP/HTTPS 的访问日志
  • error_log 记录错误日志

示例

# 如果客户端请求的文件名存在,就做什么动作
if ( -f $request_filename) {.....}

# 如果客户端请求方法是POST上传,做什么动作
if ($request_method = POST) {.....}

# 如果客户端的浏览器名称里面带有MSIE字符就做什么操作
if ($http_user_agent ~ MSIE) {
    rewrite ^(.*)$ /msie/$1 break;
}

# 不同浏览器访问不同结果(实现不同客户端(PC,安卓,IOS))访问不同的后端实例
if ($http_user_agent ~ Firefox) {
    rewrite ^(.*)$ /firefox/$1 break;
}
if ($http_user_agent ~ Chrome) {
    rewrite ^(.*)$ /chrome/$1 break;
}

# 防止盗链
location ~*\.(gif|jpg|png|swf|flv)${
    valid_referers none blocked www.xiexianbin.cn *.80.xyz;
	if ($invalid_referer) {
	    rewrite ^/(.*) https://www.xiexianbin.cn/images/forbidden.png;
	}
}

# 禁止访问以 /data 开头文件
location ~ ^/data {
    deny all;
}

# 设置某些类型文件的浏览器缓存时间
location ~ .*.(gif|jpg|jpeg|png|bmp)$ {
    expires 30d;
}

location ~ .*.(js|css)$ {
    expires 1h;
}

F&Q

The plain HTTP request was sent to HTTPS port

出现该现象是由于采用 http 协议访问 https 的端口导致的,建议修改访问协议为 https

最新评论
加载中...
Home Archives Categories Tags Statistics