如何用Nginx做端口转发

发布时间:2021-09-26 15:30:19 作者:柒染
来源:亿速云 阅读:1655

本篇文章给大家分享的是有关如何用Nginx做端口转发,小编觉得挺实用的,因此分享给大家学习,希望大家阅读完这篇文章后可以有所收获,话不多说,跟着小编一起来看看吧。

有时我们会使用一些java或node应用,但又不想让他们直接监听80端口,这时就需要用到端口转发

将域名转发到本地端口

首先介绍最常用的,将域名转发到本地另一个端口上

server{
  listen 80;
  server_name  tomcat.shaochenfeng.com;
  index  index.php index.html index.htm;

  location / {
    proxy_pass  http://127.0.0.1:8080; # 转发规则
    proxy_set_header Host $proxy_host; # 修改转发请求头,让8080端口的应用可以受到真实的请求
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
  }
}

这样访问 http://tomcat.shaochenfeng.com 时就会转发到本地的 8080 端口

将域名转发到另一个域名

server{
  listen 80;
  server_name  baidu.shaochenfeng.com;
  index  index.php index.html index.htm;

  location / {
    proxy_pass  http://www.baidu.com;
    proxy_set_header Host $proxy_host;
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
  }
}

这样访问 http://baidu.shaochenfeng.com 时就会转发到 http://www.baidu.com

本地一个端口转发到另一个端口或另一个域名

server{
  listen 80;
  server_name 127.0.0.1; # 公网ip
  index  index.php index.html index.htm;

  location / {
    proxy_pass  http://127.0.0.1:8080; # 或 http://www.baidu.com
    proxy_set_header Host $proxy_host;
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
  }
}

这样访问 http://127.0.0.1 时就会转发到本地的 8080 端口或 http://www.baidu.com

加 / 与不加 /

在配置proxy_pass代理转发时,如果后面的url加/,表示绝对根路径;如果没有/,表示相对路径

例如

  1. 加 /

    server_name shaochenfeng.com
    location /data/ {
    proxy_pass http://127.0.0.1/;
    }

    访问 http://shaochenfeng.com/data/index.html 会转发到 http://127.0.0.1/index.html

  2. 不加 /

    server_name shaochenfeng.com
    location /data/ {
    proxy_pass http://127.0.0.1;
    }

    访问 http://shaochenfeng.com/data/index.html 会转发到 http://127.0.0.1/data/index.html

以上就是如何用Nginx做端口转发,小编相信有部分知识点可能是我们日常工作会见到或用到的。希望你能通过这篇文章学到更多知识。更多详情敬请关注亿速云行业资讯频道。

推荐阅读:
  1. Nginx如何做端口转发?
  2. nginx做tcp代理

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

nginx

上一篇:如何使用Linux中用于配合管理定时任务的atrm与batch命令

下一篇:如何配置Debian系统的VPS上iptables

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》