Wd提问: nginx多个域名指向同一端口
Ai批改: 在 Nginx 中配置多个域名指向同一端口(如 80 或 443)是常见的需求,可以通过 Server Blocks(类似 Apache 的虚拟主机)实现。以下是具体配置方法和示例:
-
1、基础配置步骤
(1)创建独立的配置文件
每个域名建议单独一个配置文件(存放在 `/etc/nginx/conf.d/` 或 `/etc/nginx/sites-available/`),例如:
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.0-fpm.sock;
}
}
通过以上配置,Nginx 会根据请求的 `Host` 头将流量正确路由到对应的服务或静态资源。
0
IP地址: 113.64.201.249
搜索次数: 1
提问时间: 2025-07-13 18:21:31
热门提问:
24k足金值多少钱
嘉盛外汇公司
北京哪回收黄金镯子
ai 虚拟仿真
cxm希盟外汇平台安全吗
ai对话的原理
黄金仓库huck765cc网址
买十二生肖网址
国内贸易销售
金矿在什么岩层中
豌豆Ai站群搜索引擎系统
关于我们:
三乐Ai
作文批改
英语分析
在线翻译
拍照识图
Ai提问
英语培训
本站流量
联系我们
温馨提示:本站所有问答由Ai自动创作,内容仅供参考,若有误差请用“联系”里面信息通知我们人工修改或删除。
技术支持:本站由豌豆Ai提供技术支持,使用的最新版:《豌豆Ai站群搜索引擎系统 V.25.05.20》搭建本站。