Nginx是一款高性能的HTTP和反向代理服务器,下面是在Linux系统上安装和使用Nginx的详细步骤。
# 更新软件包列表
sudo apt update
# 安装Nginx
sudo apt install nginx
# 启动Nginx服务
sudo systemctl start nginx
# 设置开机自启
sudo systemctl enable nginx
# 添加EPEL仓库(CentOS 7/RHEL 7)
sudo yum install epel-release
# 安装Nginx
sudo yum install nginx
# 启动Nginx服务
sudo systemctl start nginx
# 设置开机自启
sudo systemctl enable nginx
sudo systemctl status nginx
安装完成后,在浏览器中输入服务器IP地址,应该能看到Nginx欢迎页面。
/etc/nginx/nginx.conf
/etc/nginx/sites-available/default
(Ubuntu/Debian) 或 /etc/nginx/conf.d/default.conf
(CentOS/RHEL)/var/www/html
# 启动Nginx
sudo systemctl start nginx
# 停止Nginx
sudo systemctl stop nginx
# 重启Nginx
sudo systemctl restart nginx
# 重新加载配置(不中断服务)
sudo systemctl reload nginx
# 检查配置语法
sudo nginx -t
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
nano /var/www/example.com/html/index.html
添加内容:
<html>
<head>
<title>Welcome to Example.com!</title>
</head>
<body>
<h1>Success! The example.com server block is working!</h1>
</body>
</html>
sudo nano /etc/nginx/sites-available/example.com
添加内容:
server {
listen 80;
listen [::]:80;
root /var/www/example.com/html;
index index.html index.htm index.nginx-debian.html;
server_name example.com www.example.com;
location / {
try_files $uri $uri/ =404;
}
}
启用配置:
sudo ln -s /etc/nginx/sites-available/example.com /etc/nginx/sites-enabled/
sudo nano /etc/nginx/conf.d/example.com.conf
添加与上面相同的内容。
sudo nginx -t
sudo systemctl reload nginx
配置Nginx作为Node.js、Python等应用的反向代理:
server {
listen 80;
server_name example.com;
location / {
proxy_pass http://localhost:3000; # 代理到本地3000端口
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection 'upgrade';
proxy_set_header Host $host;
proxy_cache_bypass $http_upgrade;
}
}
使用Let's Encrypt免费证书:
# 安装Certbot
sudo apt install certbot python3-certbot-nginx # Ubuntu/Debian
sudo yum install certbot python2-certbot-nginx # CentOS/RHEL
# 获取证书
sudo certbot --nginx -d example.com -d www.example.com
# 自动续期测试
sudo certbot renew --dry-run
/var/log/nginx/access.log
/var/log/nginx/error.log
nginx.conf
中):worker_processes auto;
events {
worker_connections 1024;
}
gzip on;
gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript;
通过以上步骤,您应该已经成功安装并配置了Nginx服务器。根据您的具体需求,可以进一步调整配置以获得更好的性能或功能。