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
nginx.exe
启动服务brew install nginx
brew services start nginx
wget https://nginx.org/download/nginx-1.25.3.tar.gz
tar -zxvf nginx-1.25.3.tar.gz
cd nginx-1.25.3
./configure
make
sudo make install
/etc/nginx/nginx.conf
(Linux) 或 conf/nginx.conf
(Windows)/etc/nginx/conf.d/
或 /etc/nginx/sites-available/
# 启动
nginx 或 systemctl start nginx
# 停止
nginx -s stop 或 systemctl stop nginx
# 重新加载配置(不中断服务)
nginx -s reload 或 systemctl reload nginx
# 测试配置是否正确
nginx -t
user www-data;
worker_processes auto;
pid /run/nginx.pid;
events {
worker_connections 1024;
}
http {
include /etc/nginx/mime.types;
default_type application/octet-stream;
access_log /var/log/nginx/access.log;
error_log /var/log/nginx/error.log;
sendfile on;
keepalive_timeout 65;
include /etc/nginx/conf.d/*.conf;
include /etc/nginx/sites-enabled/*;
}
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 443 ssl;
server_name example.com www.example.com;
ssl_certificate /etc/ssl/certs/example.com.crt;
ssl_certificate_key /etc/ssl/private/example.com.key;
ssl_protocols TLSv1.2 TLSv1.3;
ssl_ciphers HIGH:!aNULL:!MD5;
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;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
}
upstream backend {
server backend1.example.com;
server backend2.example.com;
server backend3.example.com;
}
server {
listen 80;
server_name app.example.com;
location / {
proxy_pass http://backend;
}
}
worker_processes auto; # 自动设置工作进程数为CPU核心数
events {
worker_connections 4096; # 每个工作进程的最大连接数
multi_accept on; # 一次接受多个新连接
use epoll; # Linux系统使用epoll事件模型
}
http {
sendfile on; # 启用高效文件传输模式
tcp_nopush on; # 仅在sendfile开启时有效
tcp_nodelay on; # 禁用Nagle算法
keepalive_timeout 30; # 保持连接超时时间
keepalive_requests 100; # 单个连接的最大请求数
gzip on; # 启用gzip压缩
gzip_types text/plain text/css application/json application/javascript text/xml;
open_file_cache max=1000 inactive=20s; # 文件描述符缓存
open_file_cache_valid 30s;
open_file_cache_min_uses 2;
open_file_cache_errors on;
}
server {
# 禁用不必要的HTTP方法
if ($request_method !~ ^(GET|HEAD|POST)$ ) {
return 405;
}
# 禁止访问隐藏文件
location ~ /\. {
deny all;
access_log off;
log_not_found off;
}
# 防止点击劫持
add_header X-Frame-Options "SAMEORIGIN";
# XSS保护
add_header X-XSS-Protection "1; mode=block";
# 内容安全策略
add_header Content-Security-Policy "default-src 'self';";
# 禁用服务器信息泄露
server_tokens off;
}
403 Forbidden错误
chmod -R 755 /var/www
502 Bad Gateway错误
性能问题
配置测试
nginx -t # 测试配置语法
通过以上步骤,您可以完成Nginx的安装和基本配置。根据实际需求,您可以进一步调整配置以获得更好的性能或安全性。