配置二级域名在Nginx中是一个常见需求,以下是详细的配置方法:
DNS设置
subdomain.yourdomain.com
指向服务器IPNginx配置文件
server {
listen 80;
server_name subdomain.yourdomain.com;
root /var/www/subdomain;
index index.html index.php;
location / {
try_files $uri $uri/ =404;
}
# 其他配置...
}
server {
listen 80;
server_name blog.yourdomain.com;
root /var/www/blog;
index index.html;
location / {
try_files $uri $uri/ =404;
}
}
server {
listen 80;
server_name api.yourdomain.com;
location / {
proxy_pass http://localhost:3000;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
}
server {
listen 80;
server_name shop.yourdomain.com;
root /var/www/shop;
index index.php index.html index.htm;
location / {
try_files $uri $uri/ /index.php?$args;
}
location ~ \.php$ {
include snippets/fastcgi-php.conf;
fastcgi_pass unix:/var/run/php/php7.4-fpm.sock;
}
}
server {
listen 443 ssl;
server_name subdomain.yourdomain.com;
ssl_certificate /etc/letsencrypt/live/yourdomain.com/fullchain.pem;
ssl_certificate_key /etc/letsencrypt/live/yourdomain.com/privkey.pem;
root /var/www/subdomain;
index index.html;
# 其他SSL配置...
}
server {
listen 80;
server_name subdomain.yourdomain.com;
return 301 https://$host$request_uri;
}
每次修改Nginx配置后,需要测试并重新加载:
sudo nginx -t
sudo systemctl reload nginx
确保服务器防火墙开放了80和443端口
对于生产环境,建议总是使用HTTPS
可以使用通配符证书(*.yourdomain.com)来简化多个二级域名的SSL配置
如果使用Let's Encrypt获取证书,可以使用Certbot工具:
sudo certbot --nginx -d subdomain.yourdomain.com
希望这些配置示例能帮助您成功设置Nginx二级域名。根据您的具体需求,可以调整上述配置。