在Windows系统中:
C:\Windows\System32\drivers\etc\hosts
在Linux/macOS系统中:
/etc/hosts
添加如下内容(示例):
127.0.0.1 example.test
127.0.0.1 www.example.test
在Nginx配置目录(通常为/etc/nginx/conf.d/
或/etc/nginx/sites-available/
)中创建新的配置文件:
server {
listen 80;
server_name example.test www.example.test;
root /var/www/example;
index index.html index.php;
access_log /var/log/nginx/example.access.log;
error_log /var/log/nginx/example.error.log;
location / {
try_files $uri $uri/ /index.php?$query_string;
}
location ~ \.php$ {
include fastcgi_params;
fastcgi_pass unix:/var/run/php/php7.4-fpm.sock;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
}
}
sudo mkdir -p /var/www/example
sudo chown -R $USER:$USER /var/www/example
sudo chmod -R 755 /var/www/example
echo "<h1>Welcome to Example Test Site</h1>" > /var/www/example/index.html
# 测试配置语法
sudo nginx -t
# 重启Nginx
sudo systemctl restart nginx
http://example.test
curl -I http://example.test
预期输出应包含:
HTTP/1.1 200 OK
Server: nginx/...
tail -f /var/log/nginx/example.access.log
tail -f /var/log/nginx/example.error.log
如果配置了多个域名,分别访问每个域名验证是否正确响应。
403 Forbidden错误
502 Bad Gateway错误
域名无法解析
ipconfig /flushdns
)配置不生效
/etc/nginx/sites-enabled/
目录中有符号链接sudo apt install certbot python3-certbot-nginx
sudo certbot --nginx -d example.test -d www.example.test
server {
listen 80;
server_name www.example.test;
return 301 http://example.test$request_uri;
}
upstream backend {
server backend1.example.com;
server backend2.example.com;
}
server {
location / {
proxy_pass http://backend;
}
}
通过以上步骤,您应该能够成功配置并验证Nginx下的虚拟域名。