在Linux服务器上安装和配置Nginx可以分为以下几个步骤,我将以CentOS/RHEL和Ubuntu/Debian两种主流系统为例进行说明:
# 添加EPEL仓库(针对CentOS/RHEL 7/8)
sudo yum install epel-release
# 安装Nginx
sudo yum install nginx
# 启动Nginx并设置开机自启
sudo systemctl start nginx
sudo systemctl enable nginx
# 更新软件包列表
sudo apt update
# 安装Nginx
sudo apt install nginx
# 启动Nginx并设置开机自启
sudo systemctl start nginx
sudo systemctl enable nginx
sudo systemctl status nginx
如果看到"active (running)"表示服务已启动。
# CentOS/RHEL (firewalld)
sudo firewall-cmd --permanent --add-service=http
sudo firewall-cmd --permanent --add-service=https
sudo firewall-cmd --reload
# Ubuntu/Debian (ufw)
sudo ufw allow 'Nginx Full'
浏览器访问 http://服务器IP
,看到Nginx欢迎页即表示安装成功。
Nginx的核心配置文件位于:
- 主配置文件:/etc/nginx/nginx.conf
- 站点配置:/etc/nginx/conf.d/
或 /etc/nginx/sites-available/
- 默认网站根目录:/usr/share/nginx/html
以域名 example.com
为例:
sudo nano /etc/nginx/conf.d/example.com.conf
server {
listen 80;
server_name example.com www.example.com;
root /var/www/example.com/html;
index index.html index.htm;
location / {
try_files $uri $uri/ =404;
}
# 可选:日志配置
access_log /var/log/nginx/example.com.access.log;
error_log /var/log/nginx/example.com.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
echo "<h1>Welcome to example.com</h1>" > /var/www/example.com/html/index.html
sudo nginx -t # 测试配置语法
sudo systemctl reload nginx
# 安装Certbot工具
# CentOS/RHEL:
sudo yum install certbot python3-certbot-nginx
# Ubuntu/Debian:
sudo apt install certbot python3-certbot-nginx
# 获取证书并自动配置
sudo certbot --nginx -d example.com -d www.example.com
证书会自动续期,配置保存在 /etc/letsencrypt/
。
location / {
proxy_pass http://localhost:3000; # 转发到本地Node.js应用
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
}
upstream backend {
server 192.168.1.10:80;
server 192.168.1.11:80;
}
server {
location / {
proxy_pass http://backend;
}
}
# 重载配置(不中断服务)
sudo nginx -s reload
# 测试配置文件
sudo nginx -t
# 停止/启动/重启
sudo systemctl stop nginx
sudo systemctl start nginx
sudo systemctl restart nginx
/var/log/nginx/access.log
/var/log/nginx/error.log
sudo tail -f /var/log/nginx/access.log
nginx -t
测试语法。nginx
server_tokens off;
worker_processes
和 worker_connections
参数。如果需要更具体的配置(如缓存、Gzip、安全头等),可以进一步扩展配置内容。