插件窝 干货文章 nginx服务器多站点怎么配置

nginx服务器多站点怎么配置

example 配置 Nginx index 213    来源:    2025-04-23

Nginx服务器多站点配置指南

在Nginx服务器上配置多个网站(虚拟主机)是常见的需求。以下是详细的配置方法:

基本配置方法

1. 基于端口的配置

server {
    listen 8080;
    server_name example.com;
    root /var/www/example.com;
    index index.html;

    location / {
        try_files $uri $uri/ =404;
    }
}

server {
    listen 8081;
    server_name example.org;
    root /var/www/example.org;
    index index.html;

    location / {
        try_files $uri $uri/ =404;
    }
}

2. 基于域名的配置(推荐)

server {
    listen 80;
    server_name example.com;
    root /var/www/example.com;
    index index.html;

    location / {
        try_files $uri $uri/ =404;
    }
}

server {
    listen 80;
    server_name example.org;
    root /var/www/example.org;
    index index.html;

    location / {
        try_files $uri $uri/ =404;
    }
}

最佳实践配置方式

1. 使用独立的配置文件

  1. /etc/nginx/conf.d//etc/nginx/sites-available/目录下为每个站点创建单独的配置文件
  2. /etc/nginx/sites-enabled/中创建符号链接
# 创建站点配置
sudo nano /etc/nginx/sites-available/example.com.conf

# 创建符号链接
sudo ln -s /etc/nginx/sites-available/example.com.conf /etc/nginx/sites-enabled/

2. 示例配置文件

/etc/nginx/sites-available/example.com.conf:

server {
    listen 80;
    listen [::]:80;

    server_name example.com www.example.com;
    root /var/www/example.com/public_html;

    index index.php index.html index.htm;

    access_log /var/log/nginx/example.com.access.log;
    error_log /var/log/nginx/example.com.error.log;

    location / {
        try_files $uri $uri/ /index.php?$query_string;
    }

    location ~ \.php$ {
        include snippets/fastcgi-php.conf;
        fastcgi_pass unix:/var/run/php/php7.4-fpm.sock;
    }

    location ~ /\.ht {
        deny all;
    }
}

SSL/TLS配置(HTTPS)

server {
    listen 443 ssl http2;
    listen [::]:443 ssl http2;

    server_name example.com www.example.com;

    ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem;

    root /var/www/example.com/public_html;
    index index.php index.html index.htm;

    # 其他配置...
}

# HTTP重定向到HTTPS
server {
    listen 80;
    listen [::]:80;

    server_name example.com www.example.com;

    return 301 https://$server_name$request_uri;
}

配置完成后

  1. 测试Nginx配置是否正确:

    sudo nginx -t
    
  2. 重新加载Nginx配置:

    sudo systemctl reload nginx
    

常见问题解决

  1. 配置不生效

    • 检查配置文件是否在sites-enabled目录中
    • 检查是否有语法错误(nginx -t)
    • 检查端口是否被占用
  2. 权限问题

    • 确保Nginx用户(通常是www-data)有权限访问网站目录
    • 设置正确的权限:sudo chown -R www-data:www-data /var/www/example.com
  3. 502 Bad Gateway

    • 检查PHP-FPM或其他后端服务是否运行
    • 检查fastcgi_pass指定的socket或端口是否正确

通过以上方法,您可以轻松地在单个Nginx服务器上配置多个网站。