在 Nginx 中实现一个服务配置多个站点(虚拟主机)主要有以下几种方法:
这是最常见的多站点配置方式,通过不同的域名来区分不同的站点。
在 /etc/nginx/conf.d/
目录下为每个站点创建单独的配置文件,例如:
example1.com.conf
example2.com.conf
每个配置文件内容类似:
server {
listen 80;
server_name example1.com www.example1.com;
root /var/www/example1.com;
index index.html index.php;
# 其他配置...
}
server {
listen 80;
server_name example2.com www.example2.com;
root /var/www/example2.com;
index index.html index.php;
# 其他配置...
}
sudo nginx -t
sudo systemctl restart nginx
通过不同的端口号来区分不同的站点。
server {
listen 8080;
server_name localhost;
root /var/www/site1;
index index.html;
}
server {
listen 8081;
server_name localhost;
root /var/www/site2;
index index.html;
}
如果服务器有多个IP地址,可以为每个IP配置不同的站点。
server {
listen 192.168.1.1:80;
server_name _;
root /var/www/site1;
index index.html;
}
server {
listen 192.168.1.2:80;
server_name _;
root /var/www/site2;
index index.html;
}
server {
listen 80;
server_name ~^(www\.)?(?<domain>.+)$;
root /var/www/$domain;
index index.html;
}
# /etc/nginx/conf.d/example1.com.conf
server {
listen 80;
server_name example1.com www.example1.com;
# 重定向到HTTPS
return 301 https://$host$request_uri;
}
server {
listen 443 ssl http2;
server_name example1.com www.example1.com;
ssl_certificate /etc/letsencrypt/live/example1.com/fullchain.pem;
ssl_certificate_key /etc/letsencrypt/live/example1.com/privkey.pem;
root /var/www/example1.com/public;
index index.html index.php;
access_log /var/log/nginx/example1.com.access.log;
error_log /var/log/nginx/example1.com.error.log;
location / {
try_files $uri $uri/ /index.php?$query_string;
}
location ~ \.php$ {
include fastcgi_params;
fastcgi_pass unix:/run/php/php8.1-fpm.sock;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
}
}
配置完成后,记得测试并重新加载 Nginx:
sudo nginx -t
sudo systemctl reload nginx