nginx location匹配顺序及CI框架的nginx配置

时间:2022-03-26 16:23:15

Nginx location匹配顺序如下:

  1. 用前缀字符串定义的location规则对URI进行匹配测试。
  2. =号定义了精确的前缀字符串匹配,如果发现精确匹配则使用当前规则。否则继续下一步匹配。
  3. 匹配其它普通字符串,并存储最长匹配。如果匹配以^~开始的规则,则使用当前匹配,否则继续下一步匹配。
  4. 按顺序对URI进行正则规则匹配,发现匹配后停止并使用当前匹配。若所有正则都不匹配,则使用第3步存储的最长匹配规则。
  • ~ 开头表示区分大小写的正则匹配;
  • ~* 开头表示不区分大小写的正则匹配

整体匹配优先级 =精确匹配 >  ^~前缀匹配 > 正则匹配 > 普通前缀字符串匹配

rewrite块可直接放在server段内,也可置于location段内。请求到达nginx后,URI会进行如下处理:

URI->server rewrite->new URI->location匹配

在location规则匹配过程中若对url进行了重写,则要重新开始规则匹配。若循环10次后仍没有找到真实存在的文件,服务器会返回500错误。

rewrite指令可以附带一个标志位 last/break;对此,我的理解是两者都会终止rewrite的执行,last一般用在server段,break一般用在location内。last执行完还要进行location匹配,而break则不再进行location匹配。

基于CI框架的nginx配置(windows环境):

#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;
#开启rewrite日志 测试用 rewrite日志写在error_log里
rewrite_log on;
error_log logs/error.log notice;
sendfile on;
#tcp_nopush on; #keepalive_timeout 0;
keepalive_timeout 65;
#tcp_nodelay on;
fastcgi_connect_timeout 300;
fastcgi_send_timeout 300;
fastcgi_read_timeout 300;
fastcgi_buffer_size 128k;
fastcgi_buffers 4 128k;
fastcgi_busy_buffers_size 256k;
fastcgi_temp_file_write_size 256k; #gzip on;
gzip on;
gzip_min_length 1k;
gzip_buffers 4 32k;
gzip_http_version 1.1;
gzip_comp_level 2;
gzip_types text/plain application/x-javascript text/css application/xml;
gzip_vary on;
gzip_disable "MSIE [1-6]."; server_names_hash_bucket_size 128;
client_max_body_size 100m;
client_header_buffer_size 256k;
large_client_header_buffers 4 256k; server {
listen 80;
server_name citest.com;
index index.html index.php;
root "d:/www/ci";
access_log logs/ciaccess.log main;
if (!-e $request_filename) {
rewrite ^/(.*)$ /index.php/$1 last;
} location ~ \.php(.*)$ {
fastcgi_pass 127.0.0.1:9000;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
fastcgi_param PATH_INFO $fastcgi_path_info;
fastcgi_param PATH_TRANSLATED $document_root$fastcgi_path_info;
include fastcgi_params;
} location ~ .*\.(gif|jpg|jpeg|png|bmp|swf)$ {
expires 30d;
} location ~ .*\.(js|css)?$ {
expires 12h;
}
} #include vhosts.conf;
}