挺好的链接:(反代) https://zhuanlan.zhihu.com/p/451825018
(基本命令) https://blog.csdn.net/dyeln/article/details/119451007


Nginx位置

1
/usr/local/nginx

一些文件夹简介

sbin

里面有一个nginx文件,可以看成是nginx的exe

1
2
3
total 9.9M
-rwxr-xr-x 1 root root 5.0M Oct 30 15:05 nginx
-rwxr-xr-x 1 root root 5.0M Oct 30 15:05 nginx.old

conf

字面意思 config 配置文件夹
里面很多内容,主要是nginx.conf,很多配置在这里进行

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
total 68K
-rw-r--r-- 1 root root 1.1K Oct 30 15:05 fastcgi.conf
-rw-r--r-- 1 root root 1.1K Oct 30 15:05 fastcgi.conf.default
-rw-r--r-- 1 root root 1007 Oct 30 15:05 fastcgi_params
-rw-r--r-- 1 root root 1007 Oct 30 15:05 fastcgi_params.default
-rw-r--r-- 1 root root 2.8K Oct 30 15:05 koi-utf
-rw-r--r-- 1 root root 2.2K Oct 30 15:05 koi-win
-rw-r--r-- 1 root root 5.3K Oct 30 15:05 mime.types
-rw-r--r-- 1 root root 5.3K Oct 30 15:05 mime.types.default
-rw-rw-rw- 1 root root 2.8K Nov 1 14:26 nginx.conf
-rw-r--r-- 1 root root 2.6K Oct 30 15:05 nginx.conf.default
-rw-r--r-- 1 root root 636 Oct 30 15:05 scgi_params
-rw-r--r-- 1 root root 636 Oct 30 15:05 scgi_params.default
-rw-r--r-- 1 root root 664 Oct 30 15:05 uwsgi_params
-rw-r--r-- 1 root root 664 Oct 30 15:05 uwsgi_params.default
-rw-r--r-- 1 root root 3.6K Oct 30 15:05 win-utf

修改配置(反向代理)

例如我不希望用端口访问某些资源(记不住),那么我希望nginx来帮我进行一波重定向

1
2
3
>>>  cns.com/**blog** >>> Nginx >>> cns.com:4000
甚至于 >>> localhost:4000
亦或是 >>> 101.xx.xxx.xx:4000

修改如下

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
server {
listen 80;
server_name ubuntu.cnsportiot.com;

location /blog/ {
proxy_pass http://ubuntu.cnsportiot.com:4000/;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
}

# 这是一个示例,如果您还有其他路径映射,请在这里添加更多location块。

location / {
# 默认处理或者其他路径的配置
}
}

下面是对这些Nginx配置行的解释:

location /blog/ :

这一行定义了一个Nginx location块,它指定了匹配的URL路径。在这种情况下,/blog是要匹配的路径。当客户端的请求路径以/blog开头时,此location块将生效。

proxy_pass http://ubuntu.cnsportiot.com:4000/

这是代理传递指令,指定了Nginx应该将请求代理到的目标地址。在这种情况下,请求将被代理到http://ubuntu.cnsportiot.com:4000/ ,这是您的应用程序运行的地址和端口。

proxy_set_header Host $host;:

这一行设置HTTP请求头中的Host标头。它确保在将请求代理到后端服务器时,Nginx会传递客户端请求的主机名。这对于后端服务器正确处理请求非常重要,因为它可以根据主机名来确定如何处理请求。

proxy_set_header X-Real-IP $remote_addr;:
这一行设置了一个自定义HTTP请求头X-Real-IP,并将其设置为客户端的真实IP地址。这在一些应用程序中很有用,因为它允许应用程序了解请求的真实来源。如果您的应用程序需要知道客户端的IP地址,这个设置是必要的。

这些配置行通常是必要的,特别是proxy_pass用于指定后端服务器的地址和端口,以及proxy_set_header用于设置必要的HTTP请求头。但是,是否需要设置X-Real-IP等自定义请求头取决于您的应用程序是否需要这些信息。如果您的应用程序不需要知道客户端的真实IP地址,您可以省略相关的proxy_set_header行。

验证

修改配置后应该先运行验证(语法问题)

1
/usr/local/nginx/sbin $ sudo ./nginx -t

之后应该返回

1
2
nginx: the configuration file /usr/local/nginx/conf/nginx.conf syntax is ok
nginx: configuration file /usr/local/nginx/conf/nginx.conf test is successful

重启(重载配置文件)

1
/usr/local/nginx/sbin $ sudo ./nginx -s reload

之后应该返回

什么也不返回