nginx

#user  nobody;
user  nginx nginx;
worker_processes  1;

#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;
}



http {
  upstream cacheserver {
  hash $request_uri consistent;
  keepalive 100;
  


  server     192.168.202.129:8080  fail_timeout=10s;
}
    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;
    proxy_read_timeout    300;
    proxy_connect_timeout 90;
#    proxy_set_header      Host $host;
    proxy_set_header      X-Real-IP $remote_addr;
    proxy_set_header      X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header      Proxy "";
#    proxy_set_header      Host 'www.jntianchi.com';
    #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;
        #}
 #   }

###########################################################
    # another virtual host using mix of IP-, name-, and port-based configuration
    #
    #server {
    #    listen       8000;
    #    listen       somename:8080;
    #    server_name  somename  alias  another.alias;

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


    # HTTPS server
    #
    #server {
    #    listen       443 ssl;
    #    server_name  localhost;

    #    ssl_certificate      cert.pem;
    #    ssl_certificate_key  cert.key;

    #    ssl_session_cache    shared:SSL:1m;
    #    ssl_session_timeout  5m;

    #    ssl_ciphers  HIGH:!aNULL:!MD5;
    #    ssl_prefer_server_ciphers  on;

    #    location / {
    #        root   html;
    #        index  index.html index.htm;
    #    }
    #}
include /my_page/conf/site/*.conf;
}
nginx.conf
server {
  listen *:81;
  server_name          aaa.com;

  index  index.html index.htm index.php;
  valid_referers none blocked server_names
              aaa.com/.*;

  if ($invalid_referer) {
    return 403;
 }
  valid_referers server_names


  location / {
    proxy_pass            http://cache;#是个负载均衡
    proxy_read_timeout    120;
    proxy_connect_timeout 90;
    proxy_redirect        off;
    proxy_http_version    1.1;
    proxy_set_header      Connection "";
    proxy_set_header      Host  $host;#$http_host
    proxy_set_header      X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header      X-From-IP $remote_addr;
    proxy_set_header      referer "jsjxxx.bjqjyj.cn";
  }
site.conf
server {
    listen 80;
    server_name        aaa.com;
    rewrite    ^(.*)$    https://$host$1    break;
    }

server {
        listen       443 ssl;
        server_name     aaa.com;
        ssl on;
        ssl_certificate      /my_page/conf/site/key/fullchain4.pem;
        ssl_certificate_key  /my_page/conf/site/key/privkey4.key;
        send_timeout 300s;
        set $append "-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-";
        set $cache_addr "-";
        location / {
                        proxy_pass            http://cacheserver;
                        proxy_read_timeout    300;
                        proxy_connect_timeout 90;
                        proxy_set_header      Host $host;
                        proxy_set_header      X-Real-IP $remote_addr;
                        proxy_set_header      X-Forwarded-For $proxy_add_x_forwarded_for;
                        proxy_set_header      Proxy "";
        }
}
https
tar xvzf nginx-1.3.2.tar.gz
./configure --prefix=/usr/local/nginx--with-http_stub_status_module --with-http_ssl_module --with-file-aio --with-http_realip_module
安装

 systemctl stop firewalld 
systemctl disable firewalld 
systemctl status firewalld 
vi /etc/selinux/config 

把SELINUX=enforcing 改成 SELINUX=disabled 
重启电脑就可以了。

nginx主要用来反向代理和负载均衡,底层使用epoll通信机制,理论最高支持10W并发。

nginx请求流程如下:

推荐进程数是cpu的二倍或逻辑CPU个数,优化是cpuworker绑定。

location / {

 add_header Access-Control-Allow-Origin *;

}

跨站请求,会在请求头中添加Access-Control-Allow-Origin*(get等方式)

一个request请求的流程:

  1. 初始化HTTP Request(读取来自客户端的数据,生成HTTP Request对象,该对象含有该请求所有的信息)。
  2. 处理请求头。
  3. 处理请求体。
  4. 如果有的话,调用与此请求(URL或者Location)关联的handler。
  5. 依次调用各phase handler进行处理。

ginx的特性:

基本功能:

  实现与服务静态文件(静态资源的web服务器),能缓存打开的文件描述符

  反向代理服务器,缓存、负载均衡、健康状态检测

  支持FastCGI,uwsgi

  模块化机制,非DSO机制,支持多种过滤器gzip,SSI和图像的模块完成图形大小调整等

  支持SSL

扩展功能:

  基于名称和IP做虚拟主机

  支持keeplive

  支持平滑配置更新或程序版本升级

  定制访问日志,支持使用日志缓存以提高性能

  支持URL rewrite

  支持路径别名

  支持基于IP及用户的认证:

  支持速率限制,并发数限制等

配置文件

  #用户

  user nginx;

  # master进程数

  worker_processes 8;

  #一个worker所能打开的线程数

  worker_rlimit_nofile 102400;

  #每个用户发往nginx信号队列的大小

  worker_rlimit_sigpending number 

性能:

  #worker进程个数

  worker_processes 1(通常是cpu物理个数-1)

  #后跟cpu掩码位,要分开写

  例如:

  worker_processes 2

  worker_cpu_affinity 00000001 00000010(不能完全保证这个cpu只运行这个进程,除非做cpu隔离)

  #ssl对cpu占用率比较高,有些硬件处理ssl会话,需指定那个ssl硬件

  ssl_engine device

  #每次内核时间调用(epoll)返回时,都会使用gettimeofday()系统调用,来获取当前时间来更新nginx缓存时钟,代价较大(64位机器这个代价比较小)

  timer_resolution interval

  #worker的运行优先等级

  worker_priority -10(越小,优先级越高)

事件相关:

  #是否打开nginx负载均衡锁,默认打开

  accept_mutex on|off

  #锁文件

  lock_file path

  #woker获取锁的等待时间(如果没有获取锁,必须等待这个时间默认500)

  accept_mutex_delay #ms

  #一个woker相应多个用户请求

  multi_accept on|off

  #使用时间模型

  user #method(epoll)

  #一个worker的链接数

  worker_connections

调试和定位问题:

  daemon [on|off];

   关闭提供守护进程的模式,是否让nignx运行于后台;调试时应该为off,使得所有信息直接输出在控制台,默认为on

  master_process on|off

   是否以master/worker模式运行nginx,默认为on,调试时可以设置为off以方便追踪

  error_log /path/to/error_log level

  错误日志文件及其级别,调试时可以使用debug级别,但要求在编译时必须使用--with-debug启用debug功能,默认通常为error级别

server定义虚拟主机

  listen监听端口

  default_server

  rcvbuf=SIZE

  sndbuf=SIZE

  ssl:https server

  server_name 多个按照上下顺序判断

    精确匹配

    左侧通配符匹配

    右侧通配符匹配

    正则表达式匹配 通常以~开头

  server_name_hash_bucket_size 32|64|128;快速主机名查找(个数)

location [ =|~|~*|^~](可省略) 匹配uri

location @name

  =:精确匹配

  ~:正则,区分大小写

  ~*:忽略大小写

  ^~:只需要匹配前半段uri即可

  一个server可以有多个location

  文件路径定义:

  root path一般定义在location(但在http,server,if语句中都可以使用)root只匹配到/

  location ^~/images/{

  root /web;

  }

  www.aaa.com/images/b.html 相当于/web/images这个路径下找b.html文件

  alias path指定路径别名相当于alias替换location

  location ^~/images/{

  alias /web;

  }

网络连接相关设置:

  keepalive_timeout time;

  Keepalive_requests m

  Keepalivedisanle 对方l

  tcp_ntcplay=.off on ..off.

  client_header_timeout time

  client_body_timeout time

  send_timeout time;发送相应时长

客户端请求限制

  limit_except menthod 限定不使用的相应请求,指定范围之外的其他方法的访问控制,只能用于location中

  client_max_bodt +size SIZE

  limit_rate speed 限制客户端速度字节每秒(默认0,没有限制)

  limit_rate_after time nginx响应,如果超出指定时长,则后续开始限速

  Index file ;

  定义默认页面,可以写多个值;

  error_page code ...[=[response]]  uri;

  当对于某个请求返回错误时,如果匹配是哪个了error_page 指令中设定code,重定向到指定uri。

  try__files path1 [path2...] uri;

  尝试依次访问每个路径,否则传输到最后的uri

文件操作的优化:

  sendfile on|off

  aio on|off

  open_file_cache max=N inactive-time |off

  max是最大缓存条目,满之后根据lru算法算出不活跃缓存删除

  Inactive 在指定时长内没有被访问后自动删除,默认60s(缓存的信息是元数据而不是数据,文件句柄,文件大小和上次修改时间,已经打开的目录结构,没有找到或没有访问权限的信息)

  open_file_cache_errors on|off

  open_file_cache_valid time;多久时间检查一次缓存,默认60s

  open_file_cache_min_use num 当访问次数超过num,即使超过时长也不删除

  ignore_invalid_headers on|off

  是否忽略不合法的http首部,off是严格检查

  log_not_found on|off 是否把404记录到错误日志

  resolver address 指定nginx使用dns服务器地址

  resolver_timeout 默认30s

  server_tokens 是否在错误页面显示版本号

http核心模块的主要内置变量

  $uri 当前uri不携带参数

  $host http请求头Host,没有则以处理此请求的虚拟主机名代替

  $hostname nginx运行宿主主机名

  $remote_addr: 客户端ip

  $remote_port 客户端端口

  $remote_user 使用用户认证时客户端用户的输入的用户名

  $request_filename 用户请求的uri经过本地root或alias转换后映射本地路径

  $request_method

  $server_addr

  $server_name服务器名称

  $server_protocol 服务器响应的协议版本

  $schema 协议(http或https)

  $http_HEADER 匹配请求报文中指定的HEADER例如$http_host

  $document_root 当前请求映射到的root配置项(location中的root)

access模块

  allow和deny

  auth_basic 访问文件

  auth_basic_user_file 密码文件htpasswd

  autoindex on(

  把所有url展示在前端

  )

  Charset 自动转换页面编码

  log_format compression

  access_log path compression buffer=32k 缓冲

Referer

  valid_referer    none|blocker|server_names|string

  $invalid_referer本身是布尔值

  location /{

  if ($request_method == ‘put’){

  proxy_pass http://dasda;

  }

  }

rewrite regex replacement [flag]()

  例:rewrite   ^.*/imges/(.*)$   /www/$1;

  last 停止检查rewrite,直接重新发送请求

  break 停止当前之后rewrite规则,继续由nginx进行后续操作

  redirect:302,重定向

  permanent:301,永久重定向

  如果rewrite有死循环,nginx最多循环10次,返回500错误。

  rewrite_log on|off;

  return code:接触rewrite规则并返回状态码

  stub_status 可以单独建立个server启用nginx状态服务

  gzip_static 预压缩

  gzip on|off;

原文地址:https://www.cnblogs.com/drchen/p/7978169.html