🛠️ 运维

nginx 如何配置二级域名指向本地指定端口?

要将二级域名配置为指向本地指定端口,你需要在 Nginx 的配置文件中为该二级域名设置一个独立的服务器块,并将请求代理到本地的指定端口。以下是具体的步骤:

1. 确保 DNS 设置正确

首先,确保你的二级域名(如 subdomain.example.com)已经在 DNS 设置中指向你的服务器 IP 地址。你可以在你的域名管理平台中添加一条 A 记录来实现。

2. 创建 Nginx 配置文件

为你的二级域名创建一个新的 Nginx 配置文件。在 /etc/nginx/sites-available/ 目录下创建一个文件,例如 subdomain.example.com

sudo nano /etc/nginx/sites-available/subdomain.example.com

3. 配置服务器块

在该文件中配置服务器块,使其将请求转发到本地的指定端口(例如 localhost:3000):

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

    location / {
        proxy_pass http://localhost:3000;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
    }
}
  • listen 80;:监听 80 端口,处理 HTTP 请求。
  • server_name subdomain.example.com;:指定该服务器块应用于 subdomain.example.com
  • proxy_pass http://localhost:3000;:将所有请求转发到本地的端口 3000
  • proxy_set_header:设置一些代理请求头,确保正确传递客户端信息。

4. 启用配置文件

为新创建的配置文件创建符号链接到 sites-enabled 目录:

sudo ln -s /etc/nginx/sites-available/subdomain.example.com /etc/nginx/sites-enabled/

5. 测试 Nginx 配置

在重新加载 Nginx 之前,先测试配置文件是否正确:

sudo nginx -t

如果配置正确,你将看到 syntax is oktest is successful 的提示。

6. 重新加载 Nginx

最后,重新加载 Nginx 以应用新的配置:

sudo systemctl reload nginx

7. 配置 SSL(可选)

如果你需要为二级域名启用 HTTPS,可以使用 certbot 获取 SSL 证书:

sudo certbot --nginx -d subdomain.example.com

8. 测试二级域名访问

现在,你可以通过访问 http://subdomain.example.com 来查看配置是否生效。请求应该会被转发到本地的 3000 端口,处理来自该端口的应用程序。

这样就完成了将二级域名指向本地指定端口的配置。

留言

您的邮箱地址不会被公开。 必填项已用 * 标注