nginx
精簡版Nginx配置指南(普通項目關注重點)
對于普通項目,你只需要關注以下幾個核心配置即可,其他保持默認即可良好運行:
1. 最簡生產環境配置
1.這個域名配置,其實就是一個名字,具體就是名稱,后臺不會監聽這個
server {
listen 80; # 監聽端口
server_name 192.168.10.1; # 你的域名
2.最關鍵的還是這個配置
注意后臺的請求有/api,這個才能被攔截到
# API代理(后端接口轉發)
location /api/ {
proxy_pass http://localhost:8080/; # 你的后端地址
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
}
nginx
# 主配置文件(通常位于/etc/nginx/nginx.conf或/usr/local/nginx/conf/nginx.conf)
user www-data; # 運行用戶(根據系統調整)
worker_processes auto; # 自動根據CPU核心設置工作進程
events {
worker_connections 1024; # 每個工作進程的連接數
}
http {
# 基礎設置
include mime.types; # 包含MIME類型定義
default_type application/octet-stream;
# 性能優化
sendfile on; # 啟用高效文件傳輸
keepalive_timeout 65; # 保持連接超時時間
# 日志格式
access_log /var/log/nginx/access.log;
error_log /var/log/nginx/error.log;
# 你的站點配置(可單獨放在sites-enabled/目錄)
server {
listen 80; # 監聽端口
server_name yourdomain.com; # 你的域名
# 靜態文件根目錄(Vue/React打包后的dist目錄)
root /var/www/html;
index index.html;
# 前端路由處理(SPA應用必需)
location / {
try_files $uri $uri/ /index.html;
}
# API代理(后端接口轉發)
location /api/ {
proxy_pass http://localhost:8080/; # 你的后端地址
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
}
# 靜態資源緩存
location ~* \.(js|css|png|jpg|jpeg|gif|ico)$ {
expires 30d;
access_log off;
}
}
}
2. 普通項目必須關注的5個核心配置
-
監聽端口和域名:
nginx
server { listen 80; server_name yourdomain.com; } -
靜態文件配置:
nginx
root /path/to/your/files; index index.html; -
SPA前端路由處理:
nginx
location / { try_files $uri $uri/ /index.html; } -
API代理轉發:
nginx
location /api/ { proxy_pass http://backend_server:port/; } -
基本性能優化:
nginx
sendfile on; keepalive_timeout 65;
3. 快速檢查清單
- 確保
root指向正確的靜態文件目錄 - 確認
proxy_pass的后端地址正確 - SPA項目必須有
try_files $uri $uri/ /index.html - 檢查域名(
server_name)是否正確 - 重要路徑權限正確(用戶
www-data或nginx要有訪問權限)

浙公網安備 33010602011771號