# Nginx常用操作有哪些
Nginx作為高性能的Web服務器和反向代理服務器,在互聯網服務中應用廣泛。本文將詳細介紹Nginx的常用操作,包括安裝、配置、日常管理等實用內容。
## 目錄
1. [Nginx安裝與啟動](#1-nginx安裝與啟動)
2. [基本配置管理](#2-基本配置管理)
3. [虛擬主機配置](#3-虛擬主機配置)
4. [反向代理設置](#4-反向代理設置)
5. [負載均衡配置](#5-負載均衡配置)
6. [HTTPS證書配置](#6-https證書配置)
7. [日志管理與分析](#7-日志管理與分析)
8. [性能優化技巧](#8-性能優化技巧)
9. [常見問題排查](#9-常見問題排查)
---
## 1. Nginx安裝與啟動
### Linux系統安裝
```bash
# Ubuntu/Debian
sudo apt update
sudo apt install nginx
# CentOS/RHEL
sudo yum install epel-release
sudo yum install nginx
# 啟動Nginx
sudo systemctl start nginx
# 停止Nginx
sudo systemctl stop nginx
# 重啟Nginx(平滑重啟)
sudo systemctl reload nginx
# 檢查狀態
sudo systemctl status nginx
sudo systemctl enable nginx
/etc/nginx/nginx.conf/etc/nginx/conf.d/ 或 /etc/nginx/sites-enabled/修改配置后必須測試語法:
sudo nginx -t
user www-data;
worker_processes auto;
events {
worker_connections 1024;
}
http {
include /etc/nginx/mime.types;
# 其他配置...
}
server {
listen 80;
server_name example.com;
root /var/www/example;
index index.html;
location / {
try_files $uri $uri/ =404;
}
}
通過多個server塊實現,建議每個站點使用單獨的配置文件。
location / {
proxy_pass http://backend_server;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
}
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
upstream backend {
server 192.168.1.101;
server 192.168.1.102;
}
server {
location / {
proxy_pass http://backend;
}
}
upstream backend {
server 192.168.1.101 weight=3;
server 192.168.1.102 weight=1;
}
sudo apt install certbot python3-certbot-nginx
sudo certbot --nginx -d example.com
server {
listen 443 ssl;
ssl_certificate /path/to/cert.pem;
ssl_certificate_key /path/to/key.pem;
# 其他SSL參數...
}
log_format main '$remote_addr - $remote_user [$time_local] '
'"$request" $status $body_bytes_sent '
'"$http_referer" "$http_user_agent"';
創建/etc/logrotate.d/nginx:
/var/log/nginx/*.log {
daily
missingok
rotate 14
compress
delaycompress
notifempty
create 0640 www-data adm
sharedscripts
postrotate
systemctl reload nginx
endscript
}
worker_processes auto; # 根據CPU核心數自動設置
worker_rlimit_nofile 100000; # 提高文件描述符限制
events {
worker_connections 4096;
multi_accept on;
}
gzip on;
gzip_types text/plain text/css application/json;
sudo netstat -tulnp | grep nginx
tail -f /var/log/nginx/error.log
通過掌握這些常用操作,您可以高效地管理和維護Nginx服務器。建議定期備份配置文件,并在修改前進行測試驗證。 “`
注:本文約1250字,涵蓋了Nginx的主要操作場景。實際使用時請根據具體環境調整配置參數。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。