nginx常用用法记录

168 阅读2分钟

nginx默认配置

#user  nobody;
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 {
    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;
        #}
    }


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

}

nginx正则语法

符号描述
=进行普通字符精确匹配
~波浪线表示执行一个正则匹配,区分大小写
~*表示执行一个正则匹配,不区分大小写
^~^~表示普通字符匹配,如果该选项匹配,只匹配该选项,不匹配别的选项,一般用来匹配目录
@定义命名location区段,这些区段客户端不能访问,只可以由内部产生的请求来访问,内部跳转,如try_files或error_page等
!~区分大小写不匹配
^以什么开头的匹配
$以什么结尾的匹配
\转义字符。可以转. * ?等
*代表任意字符

nginx常用命令

  1. 常见2种启动命令
> nginx // 直接nginx启动,前提是配好nginx环境变量
> systemctl start nginx.service // 使用systemctl命令启动
  1. 常见的4种停止命令
> nginx -s stop // 立即停止服务
> nginx -s quit // 从容停止服务 需要进程完成当前工作后再停止
> killall nginx //直接杀死nginx进程
> systemctl stop nginx.service // systemctl停止
  1. 常见的2种重启命令
> nginx -s reload // 重启nginx
> systemctl reload nginx.service // systemctl重启nginx
  1. 验证nginx配置文件是否正确
> nginx -t // 输出nginx.conf syntax is ok 即表示nginx的配置文件正确

配置文件的结构介绍

worker_processes  1;              			# worker进程的数量
events {                              			# 事件区块开始
    worker_connections  1024;          		        # 每个worker进程支持的最大连接数
}                               			# 事件区块结束
http {                           			# HTTP区块开始
    include       mime.types;         		        # Nginx支持的媒体类型库文件
    default_type  application/octet-stream;             # 默认的媒体类型
    sendfile        on;       			        # 开启高效传输模式
    keepalive_timeout  65;       		        # 连接超时
    include /etc/nginx/conf.d/*.conf;                   # 包含的子配置项位置和文件
    
    server {            		                # 第一个Server区块开始,表示一个独立的虚拟主机站点
        listen       80;      			        # 提供服务的端口,默认80
        server_name  localhost;    			# 提供服务的域名主机名
        location / {            	        	# 第一个location区块开始
            root   html;       			        # 站点的根目录,相当于Nginx的安装目录
            index  index.html index.htm;       	        # 默认的首页文件,多个用空格分开
        }          				        # 第一个location区块结果
        error_page   500502503504  /50x.html;           # 出现对应的http状态码时,使用50x.html回应客户
        location = /50x.html {          	        # location区块开始,访问50x.html
            root   html;      		      	        # 指定对应的站点目录为html
        }
    }  
    ......

子配置文件介绍

server {            		               
    listen       80;      			       
    server_name  localhost;    			       
    
    location / {            	        	        
        root   html;       			        
        index  index.html index.htm;       	       
    }          				                
    error_page   500502503504  /50x.html;               
    location = /50x.html {          	                
        root   html;      		      	        
    }
}  

常用变量

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

常用指令

geo

语法:  geo [$ip_variable] $variable { ... }

该指令描述了变量值对客户端 IP 地址的依赖关系。默认情况下,用于查找的 IP 地址是 $remote_addr,但从版本 0.7.27 开始,可以指定应使用哪个变量。

geo  $geo  {
    default          0;
    127.0.0.1/32     2;
    192.168.1.0/24   1;
    10.1.0.0/16      1;
}

map

语法: map $var1 $var2 { ... }

此模块允许您对一组值进行分类或映射到一组不同的值,并将结果存储在变量中。

map  $http_host  $name  {
  default          0;
 
  example.com      1;
  *.example.com    1;
  test.com         2;
  *.test.com       2;
  .site.com        3;
}

try_files

语法: try_files file1 [file2 ... filen] fallback

按顺序检查文件是否存在,返回第一个找到的文件或文件夹(结尾加斜杠/的表示文件夹),若所有的文件或文件夹都找不到,会进行一个内部重定向到最后一个参数。

location / {
    root "C:/Users/Administrator/Desktop/website";
    index index.html index.html;
    try_files $uri $uri/ /index.html; 
}

常用代码

同一个域名通过不同目录指定不同项目目录

image.png

自动适配PC/移动端页面

server {
    listen 80;
    server_name localhost;
    
    location / {
        root /usr/share/nginx/pc;                  #pc端代码目录
        if ($http_user_agent ~* '(Android |web0S | iPhone | iPod |BlackBerry)'){
            return root /usr/share/nginx/mobile;   #移动端代码目录
        }
        index index.html;
    }
}

限速

geo $limit {
    default 1;
    127.0.0.1 0;
}

map $limit $limit_number {
    1 512k;
    0 no;
}

server {
    listen       3000;
    server_name  127.0.0.1;

    location / {
        root     html;
    }

    location ~* .*.(jpg|gif|png|webp)$ {
        limit_rate $limit_number;
    }

    error_page   500 502 503 504 404 /50x.html;
    location = /50x.html {
        root   html;
    }
}

http重定向到https

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

Gzip

    gzip  on;
    gzip_static on;
    gzip_min_length 10k;
    gzip_buffers 4 16k;
    gzip_http_version 1.1;
    gzip_comp_level 6;
    gzip_types text/plain application/json;
    gzip_disable "MSIE [1-6]\.";

自适应webp

map $http_accept $webp {
    default "";
    "~*webp" ".webp";
}
	
server {
    listen       80;
    server_name  127.0.0.1;
    root   html;
        
    location ~* \.(png|jpe?g)$ {
        try_files $uri$webp $uri =404;
    }
}

ssl证书

server {
    listen       443 ssl http2;
    server_name  127.0.0.1;
       
    ssl_certificate      ../certificate/xxx.pem;
    ssl_certificate_key  ../certificate/xxx.key;

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

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

反向代理

location ^~ /api/ {
    proxy_pass   http://47.100.9.251:4002/;
    proxy_set_header Host $host;
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
        
#wss配置
location /ws {
    proxy_pass http://47.100.9.251:4003/;
    proxy_http_version 1.1;
    proxy_set_header Upgrade $http_upgrade;
    proxy_set_header Connection "upgrade";
}

多root在windows下不生效(linux未知)

server {
    listen       3000;
    server_name  127.0.0.1;

    location / {
        root     html;
    }

    location /project {
        root     web;
    }

    location /project2 {
        root     web;
    }

    error_page   500 502 503 504 404 /50x.html;
    location = /50x.html {
        root   html;
    }
}