以下是详细的Nginx安装配置指南,涵盖主流操作系统和关键配置步骤:
# Ubuntu/Debian
sudo apt update
sudo apt install nginx
# CentOS/RHEL
sudo yum install epel-release
sudo yum install nginx
# 启动并设置开机自启
sudo systemctl start nginx
sudo systemctl enable nginx
brew install nginx
brew services start nginx
nginx.exe
启动(或通过命令行操作)。/etc/nginx/nginx.conf
(Linux)或 conf/nginx.conf
(Windows)/etc/nginx/sites-available/
(需软链接到 /etc/nginx/sites-enabled/
)server {
listen 80;
server_name example.com www.example.com;
root /var/www/html;
index index.html;
location / {
try_files $uri $uri/ =404;
}
}
server {
listen 80;
server_name api.example.com;
location / {
proxy_pass http://localhost:3000; # 转发到本地3000端口
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
}
}
# 安装Certbot(Ubuntu为例)
sudo apt install certbot python3-certbot-nginx
sudo certbot --nginx -d example.com -d www.example.com
sudo certbot renew --dry-run
# 检查配置语法
sudo nginx -t
# 重新加载配置(不中断服务)
sudo nginx -s reload
# 停止/重启
sudo systemctl stop nginx
sudo systemctl restart nginx
nginx
worker_processes auto;
nginx
events {
worker_connections 1024;
}
nginx
gzip on;
gzip_types text/css application/json;
/var/log/nginx/access.log
/var/log/nginx/error.log
nginx
log_format custom '$remote_addr - $request_time';
access_log /var/log/nginx/access.log custom;
bash
sudo lsof -i :80
bash
sudo chown -R www-data:www-data /var/www/html
bash
sudo tail -f /var/log/nginx/error.log
通过以上步骤,您可以快速部署和优化Nginx。根据实际需求调整配置,如负载均衡、缓存等高级功能可进一步扩展。