在Nginx中配置多个虚拟主机(也称为"server blocks")允许你在单个服务器上托管多个网站。以下是详细配置方法:
创建虚拟主机配置文件:
/etc/nginx/conf.d/
目录(不同系统可能不同).conf
文件,例如:example1.com.conf
和example2.com.conf
基本虚拟主机配置示例:
# /etc/nginx/conf.d/example1.com.conf
server {
listen 80;
server_name example1.com www.example1.com;
root /var/www/example1.com;
index index.html index.htm;
location / {
try_files $uri $uri/ =404;
}
}
# /etc/nginx/conf.d/example2.com.conf
server {
listen 80;
server_name example2.com www.example2.com;
root /var/www/example2.com;
index index.php index.html index.htm;
location / {
try_files $uri $uri/ =404;
}
location ~ \.php$ {
include snippets/fastcgi-php.conf;
fastcgi_pass unix:/var/run/php/php7.4-fpm.sock;
}
}
如果服务器有多个IP地址:
server {
listen 192.168.1.1:80;
server_name example1.com;
root /var/www/example1.com;
# 其他配置...
}
server {
listen 192.168.1.2:80;
server_name example2.com;
root /var/www/example2.com;
# 其他配置...
}
server {
listen 8080;
server_name example1.com;
root /var/www/example1.com;
# 其他配置...
}
server {
listen 8081;
server_name example2.com;
root /var/www/example2.com;
# 其他配置...
}
为每个虚拟主机添加HTTPS支持:
server {
listen 443 ssl;
server_name example1.com www.example1.com;
ssl_certificate /etc/ssl/certs/example1.com.crt;
ssl_certificate_key /etc/ssl/private/example1.com.key;
root /var/www/example1.com;
# 其他配置...
}
当请求不匹配任何server_name
时使用的默认服务器:
server {
listen 80 default_server;
server_name _;
return 444; # 关闭连接
}
测试Nginx配置:
sudo nginx -t
重新加载Nginx:
sudo systemctl reload nginx
# 或
sudo service nginx reload
include
指令重用通用配置通过以上配置,你可以在单个Nginx服务器上高效地托管多个网站。