美文网首页
Nginx if location 指令部分应用场景使用说明

Nginx if location 指令部分应用场景使用说明

作者: awker | 来源:发表于2019-08-08 00:54 被阅读0次

    location 指令

    只有正则匹配( ~ 和 ~* )才能使用正则子串

    # cat regexp.conf 
    server {
        listen 9998;
        server_name _;
        access_log logs/regexp_access.log  main;
        index index.html index.htm;
    
        location ~ /hello/(.*)/$ {
            set $word $1;
            return 200 '$word\n';
        }
    
    }
    # curl 127.0.0.1:9998/hello/nginx/
    nginx
    

    前缀匹配(^~ )不能识别正则表达式 ,会把正则表达式当成普通字符

    # cat regexp.conf 
    server {
        listen 9998;
        server_name _;
        access_log logs/regexp_access.log  main;
        index index.html index.htm;
    
        location ^~ /hello/(.*)/$ {
            set $word $1;
            return 200 'test $word\n';
        }
    
    }
    # curl 127.0.0.1:9998/hello/nginx/
    <html>
    <head><title>404 Not Found</title></head>
    <body bgcolor="white">
    <center><h1>404 Not Found</h1></center>
    <hr><center>openresty</center>
    </body>
    </html>
    # curl 127.0.0.1:9998/hello/(.*)/$
    -bash: syntax error near unexpected token `('
    # curl 127.0.0.1:9998/hello/\(.*\)/$
    test 
    

    if 指令

    if 的优先级比 location 高,因为 if 指令在 ngx_http_server_rewrite_phase 阶段,location 指令在 ngx_http_find_config_phase 阶段。
    if 指令可以使用正则子串

    # cat regexp.conf 
    server {
        listen 9998;
        server_name _;
        access_log logs/regexp_access.log  main;
        index index.html index.htm;
    
        location ~ /hello/(.*)/$ {
            set $word $1;
            return 200 '$word\n';
        }
    
        if ($http_user_agent ~ curl/(.*)) {
            set $curl_version $1;
            return 200 'curl_version: $curl_version\n';
        }
    
    }
    # curl 127.0.0.1:9998/hello/nginx/
    curl_version: 7.29.0
    
    # cat regexp.conf 
    server {
        listen 9998;
        server_name _;
        access_log logs/regexp_access.log  main;
        index index.html index.htm;
    
        location ~ /hello/(.*)/$ {
            set $word $1;
            return 200 '$word\ncurl_version: $curl_version\n';
        }
    
        if ($http_user_agent ~ curl/(.*)) {
            set $curl_version $1;
        }
    
    }
    # curl 127.0.0.1:9998/hello/nginx/
    nginx
    curl_version: 7.29.0
    
    

    相关文章

      网友评论

          本文标题:Nginx if location 指令部分应用场景使用说明

          本文链接:https://www.haomeiwen.com/subject/stozdctx.html