sudo apt update
sudo apt install nginx
sudo systemctl start nginx
sudo systemctl enable nginx
sudo yum install epel-release
sudo yum install nginx
sudo systemctl start nginx
sudo systemctl enable nginx
brew install nginx
brew services start nginx
/etc/nginx/nginx.conf
(Linux)或conf/nginx.conf
(Windows)/etc/nginx/conf.d/
或/etc/nginx/sites-available/
server {
listen 80;
server_name example.com www.example.com;
root /var/www/example.com;
index index.html index.htm;
location / {
try_files $uri $uri/ =404;
}
}
server {
listen 80;
server_name api.example.com;
location / {
proxy_pass http://localhost:3000;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
}
}
# 启动
sudo systemctl start nginx
# 停止
sudo systemctl stop nginx
# 重启
sudo systemctl restart nginx
# 重新加载配置(不中断服务)
sudo systemctl reload nginx
# 检查配置语法
sudo nginx -t
# 查看状态
sudo systemctl status nginx
# 启动
nginx.exe
# 停止
nginx.exe -s stop
# 重新加载配置
nginx.exe -s reload
# 检查配置
nginx.exe -t
禁用服务器令牌:
server_tokens off;
限制HTTP方法:
if ($request_method !~ ^(GET|HEAD|POST)$ ) {
return 405;
}
配置SSL/TLS:
server {
listen 443 ssl;
server_name example.com;
ssl_certificate /path/to/cert.pem;
ssl_certificate_key /path/to/key.pem;
ssl_protocols TLSv1.2 TLSv1.3;
ssl_ciphers HIGH:!aNULL:!MD5;
}
设置安全头:
add_header X-Frame-Options "SAMEORIGIN";
add_header X-XSS-Protection "1; mode=block";
add_header X-Content-Type-Options "nosniff";
启用Gzip压缩:
gzip on;
gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript;
调整工作进程:
worker_processes auto; # 通常设置为CPU核心数
events {
worker_connections 1024;
}
启用缓存:
proxy_cache_path /path/to/cache levels=1:2 keys_zone=my_cache:10m inactive=60m;
server {
location / {
proxy_cache my_cache;
proxy_cache_valid 200 302 10m;
proxy_cache_valid 404 1m;
}
}
http {
log_format main '$remote_addr - $remote_user [$time_local] "$request" '
'$status $body_bytes_sent "$http_referer" '
'"$http_user_agent" "$http_x_forwarded_for"';
access_log /var/log/nginx/access.log main;
error_log /var/log/nginx/error.log warn;
}
检查Nginx是否运行:
ps aux | grep nginx
检查端口监听:
netstat -tulnp | grep nginx
查看错误日志:
tail -f /var/log/nginx/error.log
测试配置文件:
nginx -t
通过以上步骤,您可以完成Nginx的基本安装和配置。根据实际需求,您可能需要进一步调整配置参数以获得最佳性能和安全性。