还在担心80端口被单个应用占用?三步实现Nginx反向代理

1,851 阅读2分钟

携手创作,共同成长!这是我参与「掘金日新计划 · 8 月更文挑战」的第5天,点击查看活动详情

安装Nginx

快速安装

yum install -y nginx
systemctl enable nginx
systemctl start nginx

配置nginx

三步完成nginx反向代理的配置,

开启SSL记得把证书的文件放到指定的目录

# whereis nginx
vim /etc/nginx/nginx.conf

下面是/etc/nginx/nginx.conf下的nginx配置文件:

目标:请求不同子域名(80端口),请求根据子域名的不同转发请求到不同端口的后端服务上

pic.deepinsea.top:80 => pic.deepinsea.top:10001

deepinsea.top:80 www.deepinsea.top:80 公网IP:80 => http://localhost:8090

    server {
        listen       80; # 1.配置监听的端口
        listen       [::]:80;
        server_name  pic.deepinsea.top; # 2.配置被反向代理的域名
        root         /usr/share/nginx/html;
​
        # Load configuration files for the default server block.
        include /etc/nginx/default.d/*.conf;
        location / {
            proxy_pass http://pic.deepinsea.top:10001; # 3.配置代理的真实地址
            index  index.html index.htm;
            # 4.设置客户端请求体最大size,为256M,不设置会出新上传图片等大文件失败
            client_max_body_size 256M; 
        }
​
        error_page 404 /404.html;
        location = /404.html {
        }
​
        error_page 500 502 503 504 /50x.html;
        location = /50x.html {
        }
    }
   
    server {
        listen       80; # 5.监听的端口
        listen       [::]:80;
        server_name  deepinsea.top www.deepinsea.top 公网IP; # 6.自定义被代理的域名,可以多个
        root         /usr/share/nginx/html;
​
        # Load configuration files for the default server block.
        include /etc/nginx/default.d/*.conf;
        location / {
             proxy_pass http://localhost:8090; # 7.设置代理转发的真实请求地址
             index  index.html index.htm;
             # 8.set client body size to 512M  
             client_max_body_size 512M;
        }
​
        error_page 404 /404.html;
        location = /404.html {
        }
​
        error_page 500 502 503 504 /50x.html;
        location = /50x.html {
        }
    }

nginx的基本命令

# 查看Nginx的版本号
nginx -V
# 启动Nginx
# start nginx 或者 /usr/sbin/nginx
nginx
​
# 快速停止
nginx -s stop
# 正常停止
nginx -s quit
# 重启
nginx -s reopen
# 重载
nginx -s reload
​
# 查看windows任务管理器下Nginx的进程命令:
tasklist /fi "imagename eq nginx.exe"

启动Nginx

完成上述反向代理的配置之后,需要重载nginx配置文件以完成配置更新

nginx -s reload

注意:反向代理并不会导致其中一个地址不能访问,而是将请求转发到其他进程,所以真实地址与代理后的地址都可以访问

真实地址

image.png

反向代理后的地址

image.png

OK,成功完成将多个端口代理到80端口!

欢迎关注白羊🐏,感谢观看ヾ(◍°∇°◍)ノ゙