下面给你一份从零开始配置 Linux 上 Nginx的实用指南,涵盖安装 → 基础配置 → 常见场景 → 常用命令。
sudo yum install epel-release -y
sudo yum install nginx -y
sudo apt update
sudo apt install nginx -y
sudo systemctl start nginx
sudo systemctl enable nginx
验证:
systemctl status nginx
浏览器访问服务器 IP,看到 Welcome to nginx 即成功。
/etc/nginx/nginx.conf # 主配置
/etc/nginx/conf.d/*.conf # 自定义站点配置(推荐)
/etc/nginx/sites-enabled/ # Ubuntu 常用
user nginx;
worker_processes auto;
events {
worker_connections 1024;
}
http {
include mime.types;
server {
listen 80;
server_name example.com;
location / {
root /usr/share/nginx/html;
index index.html;
}
}
}
sudo mkdir -p /var/www/example
sudo echo "Hello Nginx" > /var/www/example/index.html
sudo vim /etc/nginx/conf.d/example.conf
server {
listen 80;
server_name example.com www.example.com;
root /var/www/example;
index index.html;
location / {
try_files $uri $uri/ =404;
}
}
sudo nginx -t
sudo systemctl reload nginx
server {
listen 80;
server_name api.example.com;
location / {
proxy_pass http://127.0.0.1:8080;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
}
# Ubuntu
sudo apt install certbot python3-certbot-nginx -y
# CentOS
sudo yum install certbot python3-certbot-nginx -y
sudo certbot --nginx -d example.com -d www.example.com
sudo certbot renew --dry-run
nginx -t # 检查配置
systemctl start nginx # 启动
systemctl stop nginx # 停止
systemctl reload nginx # 平滑重载
systemctl restart nginx # 重启
sudo netstat -tunlp | grep 80
# CentOS
sudo firewall-cmd --permanent --add-service=http
sudo firewall-cmd --permanent --add-service=https
sudo firewall-cmd --reload
# Ubuntu
sudo ufw allow 80
sudo ufw allow 443
chown -R nginx:nginx /var/www/example
如果你告诉我:
✅ Linux 发行版
✅ 用途(静态站 / 接口 / 前端 / 后端)
✅ 是否用域名 / HTTPS
我可以直接帮你写完整可用的 nginx 配置。