# 更新软件包列表
sudo apt update
# 安装Nginx
sudo apt install nginx -y
# 启动Nginx服务
sudo systemctl start nginx
# 设置开机自启
sudo systemctl enable nginx
# 添加EPEL仓库(CentOS 7/RHEL 7)
sudo yum install epel-release -y
# 安装Nginx
sudo yum install nginx -y
# 启动Nginx服务
sudo systemctl start nginx
# 设置开机自启
sudo systemctl enable nginx
sudo pacman -S nginx
sudo systemctl start nginx
sudo systemctl enable nginx
sudo systemctl status nginx
在浏览器中访问 http://服务器IP
,应该能看到Nginx欢迎页面。
/etc/nginx/nginx.conf
/etc/nginx/sites-available/default
(Debian/Ubuntu)/etc/nginx/conf.d/default.conf
(RHEL/CentOS)/var/log/nginx/access.log
/var/log/nginx/error.log
sudo mkdir -p /var/www/example.com/html
sudo chown -R $USER:$USER /var/www/example.com/html
sudo chmod -R 755 /var/www/example.com
echo "<html><head><title>Welcome to Example.com</title></head><body><h1>Success! The example.com server block is working!</h1></body></html>" | sudo tee /var/www/example.com/html/index.html
对于Debian/Ubuntu:
sudo nano /etc/nginx/sites-available/example.com
对于RHEL/CentOS:
sudo nano /etc/nginx/conf.d/example.com.conf
添加以下内容:
server {
listen 80;
listen [::]:80;
server_name example.com www.example.com;
root /var/www/example.com/html;
index index.html;
location / {
try_files $uri $uri/ =404;
}
}
Debian/Ubuntu:
sudo ln -s /etc/nginx/sites-available/example.com /etc/nginx/sites-enabled/
sudo nginx -t # 测试配置语法
sudo systemctl restart nginx
# 启动Nginx
sudo systemctl start nginx
# 停止Nginx
sudo systemctl stop nginx
# 重启Nginx
sudo systemctl restart nginx
# 重新加载配置(不中断服务)
sudo systemctl reload nginx
# 检查配置语法
sudo nginx -t
# 查看Nginx版本
nginx -v
如果系统启用了防火墙,需要开放HTTP(80)和HTTPS(443)端口:
# Ubuntu/Debian (ufw)
sudo ufw allow 'Nginx Full'
# RHEL/CentOS (firewalld)
sudo firewall-cmd --permanent --zone=public --add-service=http
sudo firewall-cmd --permanent --zone=public --add-service=https
sudo firewall-cmd --reload
在nginx.conf
的http块中添加:
gzip on;
gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript;
location ~* \.(jpg|jpeg|png|gif|ico|css|js)$ {
expires 30d;
add_header Cache-Control "public, no-transform";
}
# 安装Certbot
sudo apt install certbot python3-certbot-nginx -y # Debian/Ubuntu
sudo yum install certbot python3-certbot-nginx -y # RHEL/CentOS
# 获取证书
sudo certbot --nginx -d example.com -d www.example.com
# 设置自动续期
sudo certbot renew --dry-run
nginx -t
测试配置,查看错误日志/var/log/nginx/error.log
通过以上步骤,您应该能够在Linux系统上成功安装和配置Nginx服务器。根据实际需求,您可以进一步调整和优化Nginx配置。