Web服务器配置指南
Apache、Nginx配置和管理
本指南将帮助您在VPS上配置和管理Web服务器。
Apache服务器
安装Apache
# Ubuntu/Debian
apt update
apt install apache2
# CentOS/AlmaLinux
yum install httpd
systemctl enable httpd
systemctl start httpd
基本配置
# 启动Apache
systemctl start apache2
systemctl enable apache2
# 检查状态
systemctl status apache2
虚拟主机配置
# /etc/apache2/sites-available/example.com.conf
<VirtualHost *:80>
ServerName example.com
ServerAlias www.example.com
DocumentRoot /var/www/example.com
<Directory /var/www/example.com>
AllowOverride All
Require all granted
</Directory>
ErrorLog ${APACHE_LOG_DIR}/example.com_error.log
CustomLog ${APACHE_LOG_DIR}/example.com_access.log combined
</VirtualHost>
启用站点
# 启用站点
a2ensite example.com.conf
# 重载配置
systemctl reload apache2
Nginx服务器
安装Nginx
# Ubuntu/Debian
apt update
apt install nginx
# CentOS/AlmaLinux
yum install nginx
systemctl enable nginx
systemctl start nginx
Nginx配置
# /etc/nginx/sites-available/example.com
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;
}
location ~ \.php$ {
include snippets/fastcgi-php.conf;
fastcgi_pass unix:/var/run/php/php8.1-fpm.sock;
}
access_log /var/log/nginx/example.com_access.log;
error_log /var/log/nginx/example.com_error.log;
}
启用站点
# 创建软链接
ln -s /etc/nginx/sites-available/example.com /etc/nginx/sites-enabled/
# 测试配置
nginx -t
# 重载配置
systemctl reload nginx
PHP配置
安装PHP
# Ubuntu/Debian
apt install php php-fpm php-mysql php-curl php-gd php-mbstring
# CentOS/AlmaLinux
yum install php php-fpm php-mysqlnd php-curl php-gd php-mbstring
PHP-FPM配置
# 启动PHP-FPM
systemctl start php8.1-fpm
systemctl enable php8.1-fpm
# 检查状态
systemctl status php8.1-fpm
防火墙配置
Ubuntu (UFW)
ufw allow 'Apache Full'
# 或
ufw allow 'Nginx Full'
CentOS (firewalld)
firewall-cmd --permanent --add-service=http
firewall-cmd --permanent --add-service=https
firewall-cmd --reload
性能优化
Apache优化
# /etc/apache2/conf-available/performance.conf
<IfModule mod_deflate.c>
AddOutputFilterByType DEFLATE text/html text/plain text/xml text/css text/javascript application/javascript
</IfModule>
<IfModule mod_expires.c>
ExpiresActive On
ExpiresByType image/jpg "access plus 1 month"
ExpiresByType image/jpeg "access plus 1 month"
ExpiresByType image/gif "access plus 1 month"
ExpiresByType image/png "access plus 1 month"
ExpiresByType text/css "access plus 1 month"
ExpiresByType application/pdf "access plus 1 month"
ExpiresByType text/javascript "access plus 1 month"
ExpiresByType application/javascript "access plus 1 month"
</IfModule>
Nginx优化
# /etc/nginx/nginx.conf
http {
# 启用gzip压缩
gzip on;
gzip_vary on;
gzip_min_length 1024;
gzip_types text/plain text/css application/json application/javascript text/xml application/xml;
# 缓存设置
location ~* \.(jpg|jpeg|png|gif|ico|css|js)$ {
expires 1y;
add_header Cache-Control "public, immutable";
}
}