Nginx 中配置虚拟主机(也称为 server blocks)允许你在单个服务器上托管多个网站。以下是详细的配置方法:
创建配置文件:
通常虚拟主机配置文件存放在 /etc/nginx/conf.d/
或 /etc/nginx/sites-available/
目录中
基本结构:
server {
listen 80;
server_name example.com www.example.com;
root /var/www/example.com;
index index.html index.htm;
location / {
try_files $uri $uri/ =404;
}
}
server {
listen 80;
server_name site1.com www.site1.com;
root /var/www/site1;
index index.html;
access_log /var/log/nginx/site1.access.log;
error_log /var/log/nginx/site1.error.log;
}
server {
listen 80;
server_name site2.com www.site2.com;
root /var/www/site2;
index index.php index.html index.htm;
location / {
try_files $uri $uri/ /index.php?$query_string;
}
location ~ \.php$ {
include snippets/fastcgi-php.conf;
fastcgi_pass unix:/run/php/php7.4-fpm.sock;
}
}
server {
listen 443 ssl;
server_name secure.example.com;
ssl_certificate /etc/letsencrypt/live/secure.example.com/fullchain.pem;
ssl_certificate_key /etc/letsencrypt/live/secure.example.com/privkey.pem;
root /var/www/secure;
index index.html;
# SSL配置优化
ssl_protocols TLSv1.2 TLSv1.3;
ssl_prefer_server_ciphers on;
ssl_ciphers "EECDH+AESGCM:EDH+AESGCM:AES256+EECDH:AES256+EDH";
}
server {
listen 80 default_server;
listen [::]:80 default_server;
server_name _;
return 444; # 关闭连接
}
sudo nano /etc/nginx/sites-available/example.com
bash
sudo ln -s /etc/nginx/sites-available/example.com /etc/nginx/sites-enabled/
bash
sudo nginx -t
bash
sudo systemctl reload nginx
server_name
是唯一的nginx -t
测试配置语法通过以上配置,你可以在单个Nginx服务器上托管多个网站,每个网站有独立的配置和内容。