插件窝 干货文章 Nginx环境下虚拟域名如何配置及测试验证

Nginx环境下虚拟域名如何配置及测试验证

example Nginx 配置 test 494    来源:    2025-04-25

Nginx环境下虚拟域名配置及测试验证指南

一、虚拟域名配置步骤

1. 修改本地hosts文件(开发环境)

在Windows系统中:

C:\Windows\System32\drivers\etc\hosts

在Linux/macOS系统中:

/etc/hosts

添加如下内容(示例):

127.0.0.1   example.test
127.0.0.1   www.example.test

2. Nginx配置虚拟主机

在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;
    }
}

3. 创建网站目录并设置权限

sudo mkdir -p /var/www/example
sudo chown -R $USER:$USER /var/www/example
sudo chmod -R 755 /var/www/example

4. 创建测试文件

echo "<h1>Welcome to Example Test Site</h1>" > /var/www/example/index.html

5. 启用配置并重启Nginx

# 测试配置语法
sudo nginx -t

# 重启Nginx
sudo systemctl restart nginx

二、测试验证方法

1. 基本测试

  • 在浏览器访问 http://example.test
  • 检查是否显示测试页面内容

2. 命令行测试

curl -I http://example.test

预期输出应包含:

HTTP/1.1 200 OK
Server: nginx/...

3. 日志检查

tail -f /var/log/nginx/example.access.log
tail -f /var/log/nginx/example.error.log

4. 多域名测试

如果配置了多个域名,分别访问每个域名验证是否正确响应。

三、常见问题排查

  1. 403 Forbidden错误

    • 检查目录权限
    • 确保index文件存在
    • 检查SELinux状态(Linux)
  2. 502 Bad Gateway错误

    • 检查fastcgi_pass配置是否正确
    • 确认PHP-FPM服务是否运行
  3. 域名无法解析

    • 确认hosts文件修改已保存
    • 清除DNS缓存(Windows: ipconfig /flushdns
  4. 配置不生效

    • 确保配置文件在/etc/nginx/sites-enabled/目录中有符号链接
    • 确认没有其他配置冲突

四、进阶配置

HTTPS配置(使用Let's Encrypt)

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下的虚拟域名。