nginx补充001-详解 nginx location ~ .*\.(js|css)?$ 什么意思?

本文详细解析Nginx的location指令及其匹配规则,包括精确匹配、前缀匹配、正则匹配等,阐述如何高效配置静态资源和动态请求的处理流程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

语法规则: location [=|~|~*|^~] /uri/ { … }

= 开头表示精确匹配

^~ 开头表示uri以某个常规字符串开头,理解为匹配 url路径即可。nginx不对url做编码,因此请求为/static/20%/aa,可以被规则^~ /static/ /aa匹配到(注意是空格)。

~ 开头表示区分大小写的正则匹配

~*  开头表示不区分大小写的正则匹配

!~和!~*分别为区分大小写不匹配及不区分大小写不匹配 的正则

/ 通用匹配,任何请求都会匹配到。

多个location配置的情况下匹配顺序为(参考资料而来,还未实际验证,试试就知道了,不必拘泥,仅供参考):

首先匹配 =,其次匹配^~, 其次是按文件中顺序的正则匹配,最后是交给 / 通用匹配。当有匹配成功时候,停止匹配,按当前匹配规则处理请求。

例子,有如下匹配规则:

1

location = / {精确匹配,必须是127.0.0.1/

#规则A

}

location = /login {精确匹配,必须是127.0.0.1/login

#规则B

}

location ^~ /static/ {非精确匹配,并且不区分大小写,比如127.0.0.1/static/js.

#规则C

}

location ~ \.(gif|jpg|png|js|css)$ {区分大小写,以gif,jpg,js结尾

#规则D

}

location ~* \.png$ {不区分大小写,匹配.png结尾的

#规则E

}

location !~ \.xhtml$ {区分大小写,匹配不已.xhtml结尾的

#规则F

}

location !~* \.xhtml$ {

#规则G

}

location / {什么都可以

#规则H

}

那么产生的效果如下:

访问根目录/, 比如http://localhost/ 将匹配规则A

访问 http://localhost/login 将匹配规则B,http://localhost/register 则匹配规则H

访问 http://localhost/static/a.html 将匹配规则C

访问 http://localhost/a.gif, http://localhost/b.jpg 将匹配规则D和规则E,但是规则D顺序优先,规则E不起作用, 而 http://localhost/static/c.png 则优先匹配到 规则C

访问 http://localhost/a.PNG 则匹配规则E, 而不会匹配规则D,因为规则E不区分大小写。

访问 http://localhost/a.xhtml 不会匹配规则F和规则G,http://localhost/a.XHTML不会匹配规则G,因为不区分大小写。规则F,规则G属于排除法,符合匹配规则但是不会匹配到,所以想想看实际应用中哪里会用到。

访问 http://localhost/category/id/1111 则最终匹配到规则H,因为以上规则都不匹配,这个时候应该是nginx转发请求给后端应用服务器,比如FastCGI(php),tomcat(jsp),nginx作为方向代理服务器存在。

所以实际使用中,个人觉得至少有三个匹配规则定义,如下:

#这里是直接转发给后端应用服务器了,也可以是一个静态首页

# 第一个必选规则

location = / {

proxy_pass http://tomcat:8080/index

}

# 第二个必选规则是处理静态文件请求,这是nginx作为http服务器的强项

# 有两种配置模式,目录匹配或后缀匹配,任选其一或搭配使用

location ^~ /static/ {

root /webroot/static/;

}

location ~* \.(gif|jpg|jpeg|png|css|js|ico)$ {

root /webroot/res/;

}

#第三个规则就是通用规则,用来转发动态请求到后端应用服务器

#非静态文件请求就默认是动态请求,自己根据实际把握

#毕竟目前的一些框架的流行,带.php,.jsp后缀的情况很少了

location / {

proxy_pass http://tomcat:8080/

}

#直接匹配网站根,通过域名访问网站首页比较频繁,使用这个会加速处理,官网如是说。

#这里是直接转发给后端应用服务器了,也可以是一个静态首页

# 第一个必选规则

location = / {

proxy_pass http://tomcat:8080/index

}

# 第二个必选规则是处理静态文件请求,这是nginx作为http服务器的强项

# 有两种配置模式,目录匹配或后缀匹配,任选其一或搭配使用

location ^~ /static/ {

root /webroot/static/;

}

location ~* \.(gif|jpg|jpeg|png|css|js|ico)$ {

root /webroot/res/;

}

#第三个规则就是通用规则,用来转发动态请求到后端应用服务器

#非静态文件请求就默认是动态请求,自己根据实际把握

#毕竟目前的一些框架的流行,带.php,.jsp后缀的情况很少了

location / {

proxy_pass http://tomcat:8080/

}

未试验过的其他信息:

三、ReWrite语法 
last – 基本上都用这个Flag。 
break – 中止Rewirte,不在继续匹配 
redirect – 返回临时重定向的HTTP状态302 
permanent – 返回永久重定向的HTTP状态301 
1、下面是可以用来判断的表达式: 
-f和!-f用来判断是否存在文件 
-d和!-d用来判断是否存在目录 
-e和!-e用来判断是否存在文件或目录 
-x和!-x用来判断文件是否可执行 
2、下面是可以用作判断的全局变量 
例:http://localhost:88/test1/test2/test.php 
$host:localhost 
$server_port:88 
$request_uri:http://localhost:88/test1/test2/test.php 
$document_uri:/test1/test2/test.php 
$document_root:D:\nginx/html 
$request_filename:D:\nginx/html/test1/test2/test.php 
四、Redirect语法 
server { 
listen 80; 
server_name start.igrow.cn; 
index index.html index.php; 
root html; 
if ($http_host !~ “^star\.igrow\.cn$&quot { 
rewrite ^(.*) http://star.igrow.cn$1 redirect; 


五、防盗链location ~* \.(gif|jpg|swf)$ { 
valid_referers none blocked start.igrow.cn sta.igrow.cn; 
if ($invalid_referer) { 
rewrite ^/ http://$host/logo.png; 


六、根据文件类型设置过期时间 
location ~* \.(js|css|jpg|jpeg|gif|png|swf)$ { 
if (-f $request_filename) { 
expires 1h; 
break; 


七、禁止访问某个目录 
location ~* \.(txt|doc)${ 
root /data/www/wwwroot/linuxtone/test; 
deny all; 
}

++ 一些可用的全局变量 
$args 
$content_length 
$content_type 
$document_root 
$document_uri 
$host 
$http_user_agent 
$http_cookie 
$limit_rate 
$request_body_file 
$request_method 
$remote_addr 
$remote_port 
$remote_user 
$request_filename 
$request_uri 
$query_string 
$scheme 
$server_protocol 
$server_addr 
$server_name 
$server_port 
$uri

user www www; worker_processes auto; error_log /www/wwwlogs/nginx_error.log crit; pid /www/server/nginx/logs/nginx.pid; worker_rlimit_nofile 51200; stream { log_format tcp_format '$time_local|$remote_addr|$protocol|$status|$bytes_sent|$bytes_received|$session_time|$upstream_addr|$upstream_bytes_sent|$upstream_bytes_received|$upstream_connect_time'; access_log /www/wwwlogs/tcp-access.log tcp_format; error_log /www/wwwlogs/tcp-error.log; include /www/server/panel/vhost/nginx/tcp/*.conf; } events { use epoll; worker_connections 51200; multi_accept on; } http { include mime.types; #include luawaf.conf; include proxy.conf; default_type application/octet-stream; server_names_hash_bucket_size 512; client_header_buffer_size 32k; large_client_header_buffers 4 32k; client_max_body_size 50m; sendfile on; tcp_nopush on; keepalive_timeout 60; tcp_nodelay on; fastcgi_connect_timeout 300; fastcgi_send_timeout 300; fastcgi_read_timeout 300; fastcgi_buffer_size 64k; fastcgi_buffers 4 64k; fastcgi_busy_buffers_size 128k; fastcgi_temp_file_write_size 256k; fastcgi_intercept_errors on; gzip on; gzip_min_length 1k; gzip_buffers 4 16k; gzip_http_version 1.1; gzip_comp_level 2; gzip_types text/plain application/javascript application/x-javascript text/javascript text/css application/xml application/json image/jpeg image/gif image/png font/ttf font/otf image/svg+xml application/xml+rss text/x-js; gzip_vary on; gzip_proxied expired no-cache no-store private auth; gzip_disable "MSIE [1-6]\."; limit_conn_zone $binary_remote_addr zone=perip:10m; limit_conn_zone $server_name zone=perserver:10m; server_tokens off; access_log off; server { listen 888; server_name phpmyadmin; index index.html index.htm index.php; root /www/server/phpmyadmin; #error_page 404 /404.html; include enable-php.conf; location ~ .*\.(gif|jpg|jpeg|png|bmp|swf)$ { expires 30d; } location ~ .*\.(js|css)?$ { expires 12h; } location ~ /\. { deny all; } location /media { alias /www/wwwroot/media; } access_log /www/wwwlogs/access.log; } server { listen 8329; # 监听端口 server_name _; # 服务名字,多域名就写域名 location / { uwsgi_pass 0.0.0.0:8329; # django运行的端口 include uwsgi_params; # 固定搭配 } location /static{ alias /www/wwwroot/123.249.80.147_52330/static; # django收集的静态文件 } } include /www/server/panel/vhost/nginx/*.conf; } 以上nginx配置不要更改,请每一句上面加上注释
最新发布
06-09
<think>我们将在不改变原配置的前提下,为每一行配置添加注释。注释将以#开头,放在配置行的上方或右侧(根据空间)。由于配置较长,我们将分段进行注释。</think> ### Nginx配置文件详解(逐行注释版) ```nginx # 指定Nginx运行时的用户和组为www,确保安全性并限制权限[^3] user www www; # 自动设置工作进程数量(通常等于CPU核心数),优化多核处理器性能[^3] worker_processes auto; # 错误日志存储路径,crit级别记录严重错误[^3] error_log /www/wwwlogs/nginx_error.log crit; # 主进程PID文件存储位置,用于进程管理[^3] pid /www/server/nginx/logs/nginx.pid; # 设置Nginx进程最大可打开文件数限制[^4] worker_rlimit_nofile 51200; # TCP/UDP流处理模块配置开始(用于代理数据库等非HTTP服务) stream { # 自定义TCP日志格式,包含连接状态、传输数据量等关键信息 log_format tcp_format '$time_local|$remote_addr|$protocol|$status|$bytes_sent|$bytes_received|$session_time|$upstream_addr|$upstream_bytes_sent|$upstream_bytes_received|$upstream_connect_time'; # TCP访问日志存储路径和格式 access_log /www/wwwlogs/tcp-access.log tcp_format; # TCP错误日志存储路径 error_log /www/wwwlogs/tcp-error.log; # 包含TCP代理配置文件(支持热加载新增配置) include /www/server/panel/vhost/nginx/tcp/*.conf; } # 事件处理模块配置 events { # 使用epoll高性能I/O模型(Linux特有) use epoll; # 单个工作进程最大连接数 worker_connections 51200; # 允许同时接受多个新连接 multi_accept on; } # HTTP协议处理模块配置 http { # 包含MIME类型定义文件 include mime.types; # 安全防护配置文件(注释状态) #include luawaf.conf; # 包含代理相关配置(如缓存、超时等) include proxy.conf; # 默认响应类型为二进制流 default_type application/octet-stream; # 服务器名称哈希表存储空间优化 server_names_hash_bucket_size 512; # 客户端请求头缓冲区大小 client_header_buffer_size 32k; # 大型客户端请求头缓冲区配置 large_client_header_buffers 4 32k; # 客户端最大上传文件大小 client_max_body_size 50m; # 启用高效文件传输模式 sendfile on; # 数据包累积到一定大小再发送(优化传输效率) tcp_nopush on; # 客户端保持连接超时时间(秒) keepalive_timeout 60; # 禁用Nagle算法(减少小数据包延迟) tcp_nodelay on; # FastCGI相关配置开始(PHP处理) fastcgi_connect_timeout 300; # FastCGI连接超时 fastcgi_send_timeout 300; # FastCGI发送超时 fastcgi_read_timeout 300; # FastCGI读取超时 fastcgi_buffer_size 64k; # 响应缓冲区大小 fastcgi_buffers 4 64k; # FastCGI缓冲区数量和大小 fastcgi_busy_buffers_size 128k; # 忙碌时缓冲区大小 fastcgi_temp_file_write_size 256k; # 临时文件写入大小 fastcgi_intercept_errors on; # 拦截FastCGI错误 # FastCGI配置结束 # Gzip压缩配置 gzip on; # 启用gzip压缩 gzip_min_length 1k; # 最小压缩文件大小 gzip_buffers 4 16k; # gzip缓冲区配置 gzip_http_version 1.1; # 压缩适用的HTTP协议版本 gzip_comp_level 2; # 压缩级别(1-9) gzip_types text/plain application/javascript application/x-javascript text/javascript text/css application/xml application/json image/jpeg image/gif image/png font/ttf font/otf image/svg+xml application/xml+rss text/x-js; # 压缩类型 gzip_vary on; # 添加Vary响应头 gzip_proxied expired no-cache no-store private auth; # 特定场景下启用压缩 gzip_disable "MSIE [1-6]\."; # 对旧版IE禁用压缩 # 连接限制配置 limit_conn_zone $binary_remote_addr zone=perip:10m; # 按IP限制连接数 limit_conn_zone $server_name zone=perserver:10m; # 按服务器限制连接数 # 安全优化:隐藏Nginx版本信息 server_tokens off; # 禁用访问日志(生产环境建议开启) access_log off; # phpMyAdmin服务配置 server { # 监听888端口 listen 888; # 服务器名称为phpmyadmin server_name phpmyadmin; # 默认索引文件顺序 index index.html index.htm index.php; # 网站根目录 root /www/server/phpmyadmin; # 启用PHP处理配置(由include文件具体定义) include enable-php.conf; # 静态资源缓存设置 location ~ .*\.(gif|jpg|jpeg|png|bmp|swf)$ { expires 30d; # 30天缓存 } location ~ .*\.(js|css)?$ { expires 12h; # 12小时缓存 } # 禁止访问隐藏文件(以.开头) location ~ /\. { deny all; } # 媒体文件特殊路径 location /media { alias /www/wwwroot/media; # 别名映射 } # 当前服务器的访问日志位置 access_log /www/wwwlogs/access.log; } # Django应用服务配置 server { # 监听8329端口 listen 8329; # 通用服务器名称(匹配所有域名) server_name _; # 主请求处理 location / { uwsgi_pass 127.0.0.1:8329; # 转发到Django的uWSGI端口 include uwsgi_params; # 包含uWSGI标准参数 } # 静态文件处理 location /static { alias /www/wwwroot/123.249.80.147_52330/static; # 静态文件目录映射 } } # 包含所有虚拟主机配置文件(支持热加载) include /www/server/panel/vhost/nginx/*.conf; ``` ### 关键配置分析 1. **流处理模块**:通过 `stream {}` 块实现TCP/UDP层代理(如数据库代理)[^2] 2. **性能优化**: - `worker_processes auto` 自动匹配CPU核心数 - `epoll` 模型高效处理高并发连接 - `gzip` 压缩减少网络传输量 3. **安全配置**: - 隐藏Nginx版本(`server_tokens off`) - 限制客户端请求大小(`client_max_body_size`) - 禁止访问隐藏文件(`location ~ /\.`) 4. **动态加载**:通过 `include` 指令实现配置模块化[^4] 5. **应用服务**: - phpMyAdmin服务(888端口) - Django应用(8329端口+uWSGI协议)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值