nginx日常报错解决

1. 问题一

报错:

nginx: [emerg] "proxy_pass" cannot have URI part in location given by regular expression, or inside named location, or inside "if" statement, or inside "limit_except" block in /lingtian/opt/nginx/conf/vhost/test.conf:46

描述:

# 当nginx的location使用~或~*等正则表达式时,proxy_pass不能在后面等url中加 / 去掉location的内容,如:
location ~* /test {
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $http_x_forwarded_for;
        proxy_set_header Host  $host;
        proxy_set_header Connection "";
        proxy_pass      http://127.0.0.1/;   # 想要通过此 / 去掉test后去请求http://127.0.0.1,如127.0.0.1/test/123 --> 127.0.0.1/123
}

解决:

# 1. 不使用正则表达式,如下:
location /test {    # 正则不允许,那就不用呗,但是这里不区分大小写了,⚠️
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $http_x_forwarded_for;
        proxy_set_header Host  $host;
        proxy_set_header Connection "";
        proxy_pass      http://127.0.0.1/;   
}

# 2. 通过 $ 符号传递变量
location /test/(.*) {
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $http_x_forwarded_for;
        proxy_set_header Host  $host;
        proxy_set_header Connection "";
        proxy_pass      http://127.0.0.1/$1;   # 此处$1是上面location中的括号内的内容
}

# 3. 通过lua来实现,这里不做介绍,有兴趣自行学习

posted @ 2022-01-17 15:21  焦耳|程  阅读(2172)  评论(0编辑  收藏  举报