在Nginx服务器上配置多个网站(虚拟主机)是常见的需求。以下是详细的配置方法:
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;
}
}
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;
}
}
/etc/nginx/conf.d/
或/etc/nginx/sites-available/
目录下为每个站点创建单独的配置文件/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/
/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;
}
}
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;
}
测试Nginx配置是否正确:
sudo nginx -t
重新加载Nginx配置:
sudo systemctl reload nginx
配置不生效:
sites-enabled
目录中nginx -t
)权限问题:
www-data
)有权限访问网站目录sudo chown -R www-data:www-data /var/www/example.com
502 Bad Gateway:
通过以上方法,您可以轻松地在单个Nginx服务器上配置多个网站。