nginx 配置 子域名 指向 服务端口

3,717 阅读2分钟

前言

安装:www.nginx.com/resources/w…

服务器上在不同端口存在网络服务,例如:域名为 example.com 服务器上 localhost:2236 提供博客服务,localhost:2237提供其它的服务,等等。相较于输入不同的端口,我们可能更倾向于输入子域名来达到访问不同服务的目的。例如 blog.example.com 指向 localhost:2236 ; other.example.com 指向 localhost:2237.

配置步骤

环境

假设

  • 服务器 ip:xx.xx.xx.xx
  • 域名:example.com

并且 执行 ping example.com 解析的ip为 xx.xx.xx.xx

添加子域名解析

首先添加子域名解析记录。因为我的域名解析是在 cloudflare 上完成的,所以以此为例,在 cloudflare 上添加

类型名称内容TTL代理状态
Ablogxx.xx.xx.xx自动仅限 DNS
Aotherxx.xx.xx.xx自动仅限 DNS

添加完毕后等待解析生效,或者可以在本地添加域名解析进行接下来的步骤

【注】要注意 代理状态 的选择,不要选择 【已代理】 选项,确保解析的是实际的ip:xx.xx.xx.xx

nginx 添加配置

安装完 nginx 后,可以通过 nginx -t 来查看其配置文件位置以及状态

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

打开配置文件可以看到此处配置

    # Load modular configuration files from the /etc/nginx/conf.d directory.
    # See http://nginx.org/en/docs/ngx_core_module.html#include
    # for more information.
    include /etc/nginx/conf.d/*.conf;

因此可以在 /etc/nginx/conf.d/ 文件夹下创建后缀为 .conf 的配置文件。创建 blog.example.com.conf 文件:

[root@185]# > blog.example.com.conf

编辑 blog.example.com.conf 文件添加以下配置内容:

server {
    listen 80;
    server_name blog.example.com;

    location / {
        proxy_pass http://localhost:2236;
    }
}

完成后重新加载配置

[root@185]# systemctl reload nginx

最后访问 blog.example.com 就可以看到博客的服务了

todo

https