想用nginx转发内网IPa到内网IPb 但是配置文件提示错误

nginx version: nginx/1.23.1

想转发内网IP 10.0.3.2的端口10000-12000到内网IP 10.0.3.3,并且提供访问的真实IP,参照着写了个配置文件但是不能使用。

配置文件格式:
server {
listen 10000-12000;
server_name _;
location / {
proxy_pass "http://10.0.3.3:$server_port";
proxy_redirect off;
proxy_http_version 1.1;
proxy_set_header Upgrade "$http_upgrade";
proxy_set_header Connection "upgrade";
proxy_set_header Host "$http_host";
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_intercept_errors on;
}
}

nginx -t报错

nginx: [emerg] "server" directive is not allowed here in /etc/ngi
nx/conf.d/default.conf:1
nginx: configuration file /etc/nginx/conf.d/default.conf test fai
led

检查配置文件的格式,花括号是否都能匹配正确。另外,这一句:server_name _; 咋回事? server_name 后面的下划线多了吧

语法没看出问题,server_name 的值取下划线作为输入,用于作为 fallthrough 的路由提供也没有问题。重点排查 default.conf 有没有哪里的什么关键字写错,或者漏了分号这些低级错误。有条件的可以给出整个 default.conf 给大家看看。

毫无疑问是配置出了问题,配置测试不通过,请检查/etc/nginx/conf.d/default.conf配置文件

配置文件有问题,检查一下

server_name _这样就好啦,你的是server_name和最后一个下划线之间没有空格。

有时候文件是正确无误,但是也会报错。
实际问题是进行语法检测的对象有问题;
要检测现有的修改过的Nginx配置是否有错误,不是只检测 .conf文件,而是不管任何时候,始终都是去检测主文件/etc/nginx/nginx.conf,只有这样,才能顺利的在对应的模块加载.conf 文件。
这样保证了配置的前后语境的正确性,这样才是真正的检测。
所以正确的检测修改的Nginx的语法是否错误的命令应该是: nginx -t -c /etc/nginx/nginx.conf ,如果配置文件有异常,会直接报出,否则就是

[root@op-2:~# nginx -t -c /etc/nginx/nginx.conf
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful

[root@op-2:~# nginx -t
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful

是不是外面少写了http层,server要嵌入在http{}里面。

我用的版本是:NGINX_VERSION=1.21.5,测试没有问题。还有一个问题就是你work_connection配置了多少:2001吗?

img


你的nginx.conf配置文件中一定要将http{ defalut.conf 这个配置文件}