Nginx可以通过虚拟主机(server blocks)来配置多个网站。以下是详细的配置方法:
server {
listen 80;
server_name example.com www.example.com;
root /var/www/example.com;
index index.html index.php;
location / {
try_files $uri $uri/ =404;
}
}
server {
listen 80;
server_name example2.com www.example2.com;
root /var/www/example2.com;
index index.html index.php;
location / {
try_files $uri $uri/ =404;
}
}
server {
listen 8080;
server_name example.com;
root /var/www/example.com;
index index.html;
}
server {
listen 8081;
server_name example2.com;
root /var/www/example2.com;
index index.html;
}
server {
listen 192.168.1.10:80;
server_name example.com;
root /var/www/example.com;
index index.html;
}
server {
listen 192.168.1.11:80;
server_name example2.com;
root /var/www/example2.com;
index index.html;
}
/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/
server {
listen 80;
server_name example.com www.example.com;
root /var/www/example.com/public;
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:/run/php/php8.1-fpm.sock;
}
location ~ /\.ht {
deny all;
}
}
server {
listen 80;
server_name example.com www.example.com;
return 301 https://$server_name$request_uri;
}
server {
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;
include /etc/letsencrypt/options-ssl-nginx.conf;
ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem;
root /var/www/example.com/public;
index index.php index.html index.htm;
# 其他配置...
}
配置不生效
sudo nginx -t
sudo systemctl reload nginx
权限问题
sudo chown -R www-data:www-data /var/www/example.com
sudo chmod -R 755 /var/www/example.com
PHP不执行
重定向循环
server {
listen 80;
server_name *.example.com;
set $subdomain "";
if ($host ~* ^([a-z0-9-]+)\.example\.com$) {
set $subdomain $1;
}
root /var/www/example.com/$subdomain;
}
upstream backend {
server backend1.example.com;
server backend2.example.com;
}
server {
location / {
proxy_pass http://backend;
}
}
location ~* \.(jpg|jpeg|png|gif|ico|css|js)$ {
expires 30d;
add_header Cache-Control "public, no-transform";
}
配置完成后,记得测试并重新加载Nginx:
sudo nginx -t
sudo systemctl reload nginx