Nginx 基本使用和高級(jí)用法示例詳解
Nginx 基本使用和高級(jí)用法詳解
一、Nginx 簡介
Nginx 是一個(gè)高性能的 HTTP 和反向代理服務(wù)器,具有占用內(nèi)存少、并發(fā)能力強(qiáng)等特點(diǎn),廣泛應(yīng)用于 Web 服務(wù)、負(fù)載均衡、靜態(tài)資源處理和反向代理等場(chǎng)景。
二、基本安裝與使用
1. 安裝 Nginx
Ubuntu/Debian
sudo apt update sudo apt install nginx
CentOS/RHEL
sudo yum install nginx # 或 sudo dnf install nginx
2. 基本操作命令
# 啟動(dòng) sudo systemctl start nginx # 停止 sudo systemctl stop nginx # 重啟 sudo systemctl restart nginx # 重新加載配置(不中斷服務(wù)) sudo systemctl reload nginx # 查看狀態(tài) sudo systemctl status nginx # 開機(jī)自啟 sudo systemctl enable nginx
三、配置文件結(jié)構(gòu)
1. 主要配置文件目錄結(jié)構(gòu)
/etc/nginx/ ├── nginx.conf # 主配置文件 ├── conf.d/ # 額外配置文件目錄 ├── sites-available/ # 可用站點(diǎn)配置文件 └── sites-enabled/ # 已啟用站點(diǎn)配置文件(軟鏈接指向 sites-available)
2. 基本配置示例(/etc/nginx/nginx.conf)
user nginx;
worker_processes auto;
error_log /var/log/nginx/error.log;
pid /run/nginx.pid;
events {
worker_connections 1024;
use epoll;
multi_accept on;
}
http {
include /etc/nginx/mime.types;
default_type application/octet-stream;
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;
sendfile on;
tcp_nopush on;
tcp_nodelay on;
keepalive_timeout 65;
types_hash_max_size 2048;
include /etc/nginx/conf.d/*.conf;
include /etc/nginx/sites-enabled/*;
}四、虛擬主機(jī)配置
1. 基本虛擬主機(jī)配置
# /etc/nginx/sites-available/example.com
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;
}
# 靜態(tài)資源緩存優(yōu)化
location ~* \.(jpg|jpeg|png|gif|ico|css|js)$ {
expires 1y;
add_header Cache-Control "public, immutable";
}
}2. 啟用站點(diǎn)
# 創(chuàng)建軟鏈接啟用站點(diǎn) sudo ln -s /etc/nginx/sites-available/example.com /etc/nginx/sites-enabled/ # 測(cè)試配置是否正確 sudo nginx -t # 重新加載配置 sudo systemctl reload nginx
五、高級(jí)配置技巧
1. 反向代理配置
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;
proxy_set_header X-Forwarded-Proto $scheme;
# 超時(shí)設(shè)置
proxy_connect_timeout 30s;
proxy_send_timeout 30s;
proxy_read_timeout 30s;
# 緩沖設(shè)置
proxy_buffering on;
proxy_buffer_size 4k;
proxy_buffers 8 4k;
}
}2. 負(fù)載均衡
upstream backend {
server backend1.example.com weight=3;
server backend2.example.com;
server backend3.example.com;
server backup.example.com backup;
}
server {
listen 80;
server_name app.example.com;
location / {
proxy_pass http://backend;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
}
}3. SSL/TLS 配置
server {
listen 443 ssl http2;
server_name example.com;
ssl_certificate /etc/ssl/certs/example.com.crt;
ssl_certificate_key /etc/ssl/private/example.com.key;
# SSL 安全設(shè)置
ssl_protocols TLSv1.2 TLSv1.3;
ssl_ciphers ECDHE-RSA-AES128-GCM-SHA256:ECDHE-RSA-AES256-GCM-SHA384;
ssl_prefer_server_ciphers off;
# HSTS 強(qiáng)制 HTTPS
add_header Strict-Transport-Security "max-age=63072000" always;
root /var/www/example.com;
index index.html;
}4. 緩存配置
代理緩存
proxy_cache_path /var/cache/nginx levels=1:2 keys_zone=my_cache:10m max_size=10g
inactive=60m use_temp_path=off;
server {
location / {
proxy_cache my_cache;
proxy_pass http://backend;
proxy_cache_valid 200 302 10m;
proxy_cache_valid 404 1m;
add_header X-Cache-Status $upstream_cache_status;
}
}靜態(tài)資源緩存
location ~* \.(js|css|png|jpg|jpeg|gif|ico|svg)$ {
expires 1y;
add_header Cache-Control "public, immutable";
}5. 安全配置
# 隱藏版本號(hào)
server_tokens off;
# 安全響應(yīng)頭
add_header X-Frame-Options "SAMEORIGIN" always;
add_header X-XSS-Protection "1; mode=block" always;
add_header X-Content-Type-Options "nosniff" always;
add_header Referrer-Policy "no-referrer-when-downgrade" always;
add_header Content-Security-Policy "default-src 'self' http: https: data: blob: 'unsafe-inline'" always;
# 上傳大小限制
client_max_body_size 10m;
# 限制非法請(qǐng)求方法
if ($request_method !~ ^(GET|POST|HEAD)$) {
return 405;
}6. 限流配置
# 定義限流區(qū)域
limit_req_zone $binary_remote_addr zone=api:10m rate=10r/s;
limit_req_zone $binary_remote_addr zone=login:10m rate=2r/m;
server {
location /api/ {
limit_req zone=api burst=20 nodelay;
proxy_pass http://backend;
}
location /login {
limit_req zone=login burst=5;
proxy_pass http://backend;
}
}7. URL 重寫和重定向
server {
# 強(qiáng)制跳轉(zhuǎn) HTTPS
if ($scheme = http) {
return 301 https://$server_name$request_uri;
}
# 路徑重定向
location /old-path {
return 301 /new-path;
}
# 去除 .html 擴(kuò)展名
location / {
try_files $uri $uri.html $uri/ =404;
}
# RESTful URL 重寫
location /api/v1/users {
rewrite ^/api/v1/users/(.*)$ /api/v1/users?id=$1 last;
}
}8. Gzip 壓縮
gzip on;
gzip_vary on;
gzip_min_length 1024;
gzip_proxied any;
gzip_comp_level 6;
gzip_types
text/plain
text/css
text/xml
text/javascript
application/json
application/javascript
application/xml+rss
application/atom+xml
image/svg+xml;六、性能優(yōu)化配置
1. 連接優(yōu)化
events {
worker_connections 4096;
use epoll;
multi_accept on;
}
http {
sendfile on;
tcp_nopush on;
tcp_nodelay on;
keepalive_timeout 65;
keepalive_requests 1000;
# 文件描述符緩存
open_file_cache max=200000 inactive=20s;
open_file_cache_valid 30s;
open_file_cache_min_uses 2;
open_file_cache_errors on;
}2. 工作進(jìn)程優(yōu)化
worker_processes auto; worker_cpu_affinity auto; # 提高文件描述符限制 worker_rlimit_nofile 65535;
七、日志配置
1. 自定義日志格式
log_format main '$remote_addr - $remote_user [$time_local] "$request" '
'$status $body_bytes_sent "$http_referer" '
'"$http_user_agent" "$http_x_forwarded_for" '
'rt=$request_time uct="$upstream_connect_time" '
'uht="$upstream_header_time" urt="$upstream_response_time"';
access_log /var/log/nginx/access.log main;
error_log /var/log/nginx/error.log warn;2. 日志分割腳本(rotate_nginx_logs.sh)
#!/bin/bash
# rotate_nginx_logs.sh
LOG_DIR="/var/log/nginx"
DATE=$(date -d "yesterday" +%Y-%m-%d)
mv $LOG_DIR/access.log $LOG_DIR/access.$DATE.log
mv $LOG_DIR/error.log $LOG_DIR/error.$DATE.log
# 通知 Nginx 重新打開日志文件
kill -USR1 $(cat /var/run/nginx.pid)
# 壓縮7天前的日志
find $LOG_DIR -name "*.log" -mtime +7 -exec gzip {} \;提示:可配合
cron定時(shí)執(zhí)行日志輪轉(zhuǎn)。
八、監(jiān)控和調(diào)試
1. 狀態(tài)頁面配置
server {
listen 8080;
server_name localhost;
location /nginx_status {
stub_status on;
access_log off;
allow 127.0.0.1;
deny all;
}
}訪問 http://localhost:8080/nginx_status 可查看連接狀態(tài)。
2. 調(diào)試常用命令
# 測(cè)試配置語法 sudo nginx -t # 打印完整配置(含 include) sudo nginx -T # 查看 Nginx 編譯參數(shù)和模塊 nginx -V # 實(shí)時(shí)查看日志 tail -f /var/log/nginx/access.log tail -f /var/log/nginx/error.log # 壓力測(cè)試(Apache Bench) ab -n 1000 -c 100 http://example.com/
九、Docker 中的 Nginx
1. Dockerfile 示例
FROM nginx:alpine COPY nginx.conf /etc/nginx/nginx.conf COPY sites/ /etc/nginx/sites-available/ COPY html/ /usr/share/nginx/html/ RUN ln -s /etc/nginx/sites-available/example.com /etc/nginx/sites-enabled/ EXPOSE 80 443 CMD ["nginx", "-g", "daemon off;"]
2. Docker Compose 示例
version: '3.8'
services:
nginx:
image: nginx:alpine
ports:
- "80:80"
- "443:443"
volumes:
- ./nginx.conf:/etc/nginx/nginx.conf
- ./sites:/etc/nginx/sites-available
- ./html:/usr/share/nginx/html
- ./ssl:/etc/ssl
networks:
- webnet
networks:
webnet:
driver: bridge結(jié)語
本指南涵蓋了 Nginx 的 基礎(chǔ)安裝、虛擬主機(jī)、反向代理、負(fù)載均衡、SSL 配置、緩存、安全加固、限流、URL 重寫、Gzip 壓縮、性能調(diào)優(yōu)、日志管理、監(jiān)控調(diào)試 以及 Docker 部署 等核心內(nèi)容,適用于構(gòu)建高可用、高性能、安全的 Web 服務(wù)架構(gòu)。
建議在生產(chǎn)環(huán)境中結(jié)合具體業(yè)務(wù)場(chǎng)景進(jìn)行配置優(yōu)化,并定期審查安全策略和性能指標(biāo)。
到此這篇關(guān)于Nginx 基本使用和高級(jí)用法詳解的文章就介紹到這了,更多相關(guān)nginx 安裝使用內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Nginx中roxy_set_header與add_header區(qū)別舉例淺析
proxy_set_header是一個(gè) Nginx 配置指令,用于設(shè)置將要轉(zhuǎn)發(fā)到后端服務(wù)器的 HTTP 請(qǐng)求頭,這篇文章主要給大家介紹了關(guān)于Nginx中roxy_set_header與add_header區(qū)別的相關(guān)資料,需要的朋友可以參考下2024-04-04
nginx中的兩個(gè)模塊的proxy_pass的區(qū)別解析
在nginx中配置proxy_pass代理轉(zhuǎn)發(fā)時(shí),如果在proxy_pass后面的url加/,表示絕對(duì)根路徑;如果沒有/,表示相對(duì)路徑,把匹配的路徑部分也給代理走。本文給大家介紹nginx中的兩個(gè)模塊的proxy_pass的區(qū)別,感興趣的朋友一起看看吧2021-11-11
Nginx?error_page自定義錯(cuò)誤頁面設(shè)置過程
這篇文章主要介紹了Nginx?error_page自定義錯(cuò)誤頁面設(shè)置過程,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-12-12
Nginx部署多個(gè)vue項(xiàng)目的方法步驟
本文主要介紹了Nginx部署多個(gè)vue項(xiàng)目的方法步驟,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2023-06-06
如何在centos上使用yum安裝rabbitmq-server
這篇文章主要介紹了如何在centos上使用yum安裝rabbitmq-server,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-09-09
Nginx配置server_name為域名后無法訪問的問題解決
在Nginx的配置文件中增加服務(wù)器,其server_name設(shè)置為域名時(shí),該網(wǎng)址不能正常訪問,所以本文給大家介紹了Nginx配置server_name為域名后無法訪問的問題解決,需要的朋友可以參考下2024-01-01

