w w w . w d . c h a t
🗣 Wd提问
nginx多个域名指向同一端口
🤖 Ai回答
在 Nginx 中配置多个域名指向同一端口(如 80 或 443)是常见的需求,可以通过 Server Blocks(类似 Apache 的虚拟主机)实现。以下是具体配置方法和示例:

1、基础配置步骤
(1)创建独立的配置文件
每个域名建议单独一个配置文件(存放在 `/etc/nginx/conf.d/` 或 `/etc/nginx/sitesavailable/`),例如:
bash
sudo nano /etc/nginx/conf.d/domain1.conf
sudo nano /etc/nginx/conf.d/domain2.conf

(2)配置 Server Block
每个文件通过 `server_name` 区分域名,监听同一端口(如 80):
nginx
domain1.conf
server {
listen 80;
server_name domain1.com www.domain1.com;

root /var/www/domain1;
index index.html;

location / {
try_files $uri $uri/ =404;
}
}

nginx
domain2.conf
server {
listen 80;
server_name domain2.com www.domain2.com;

root /var/www/domain2;
index index.html;

location / {
try_files $uri $uri/ =404;
}
}

(3)检查配置并重载 Nginx
bash
sudo nginx t 测试配置语法
sudo systemctl reload nginx

2、进阶场景
(1)HTTPS 配置(端口 443)
为每个域名配置 SSL 证书:
nginx
server {
listen 443 ssl;
server_name domain1.com;

ssl_certificate /path/to/domain1.crt;
ssl_certificate_key /path/to/domain1.key;

root /var/www/domain1;
index index.html;
}

(2)默认服务器处理
防止未匹配的域名指向错误内容:
nginx
server {
listen 80 default_server;
server_name _;
return 444; 关闭连接或跳转到其他页面
}

(3)反向代理到不同服务
根据域名代理到不同后端:
nginx
server {
listen 80;
server_name app.domain.com;

location / {
proxy_pass http://localhost:3000; 指向本地的 Node.js 服务
}
}

server {
listen 80;
server_name api.domain.com;

location / {
proxy_pass http://localhost:5000; 指向另一个后端服务
}
}

3、注意事项
1、DNS 解析:确保所有域名已解析到服务器的 IP 地址。
2、证书管理:使用 Let's Encrypt 的 `certbot` 可自动配置多域名 HTTPS:
bash
sudo certbot nginx d domain1.com d domain2.com

3、性能优化:大量域名时,合并配置或使用通配符证书(如 `*.example.com`)。

4、完整示例
nginx
域名A
server {
listen 80;
server_name shop.example.com;

root /var/www/shop;
index index.html;
}

域名B(HTTPS)
server {
listen 443 ssl;
server_name blog.example.com;

ssl_certificate /etc/letsencrypt/live/blog.example.com/fullchain.pem;
ssl_certificate_key /etc/letsencrypt/live/blog.example.com/privkey.pem;

root /var/www/blog;
index index.php;

location ~ \.php$ {
include fastcgi_params;
fastcgi_pass unix:/var/run/php/php8.0fpm.sock;
}
}

通过以上配置,Nginx 会根据请求的 `Host` 头将流量正确路由到对应的服务或静态资源。
0
📍
IP地址 160.246.240.210
🔍
搜索次数 12
提问时间 2025-08-05 13:06:53

📣 商家广告
高防vps

单字符域名

单字符域名

贵阳用友软件

贵阳用友软件

🛒 域名购买

热门提问

🌐 域名评估

最新挖掘

🖌 热门作画

🤝 关于我们

🗨 加入群聊
💬选择任意群聊,与同好交流分享

🔗 友情链接

🧰

站长工具

📢

温馨提示

本站所有 ❓️ 问答 由Ai自动创作,内容仅供参考,若有误差请用"联系"里面信息通知我们人工修改或删除。

👉

技术支持

本站由 🟢 豌豆Ai 提供技术支持,使用的最新版: 《豌豆Ai站群搜索引擎系统 V.25.10.25》 搭建本站。

上一篇 354319 354320 354321 下一篇