搭建静态服务器
使用 Nginx 搭建一个功能完整、安全、高性能的静态资源 Web 服务器
基本配置文件
通过编译安装的 nginx 的配置文件在 /usr/local/nginx/conf/ 目录,当前默认的配置文件目录 /usr/local/nginx/conf/nginx.conf
nginx
#user nobody;
worker_processes 1;
#error_log logs/error.log;
#error_log logs/error.log notice;
#error_log logs/error.log info;
#pid logs/nginx.pid;
events {
worker_connections 1024;
}
http {
include 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 logs/access.log main;
sendfile on;
#tcp_nopush on;
#keepalive_timeout 0;
keepalive_timeout 65;
#gzip on;
server {
listen 80;
server_name localhost;
#charset koi8-r;
#access_log logs/host.access.log main;
location / {
root html;
index index.html index.htm;
}
#error_page 404 /404.html;
# redirect server error pages to the static page /50x.html
#
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root html;
}
# proxy the PHP scripts to Apache listening on 127.0.0.1:80
#
#location ~ \.php$ {
# proxy_pass http://127.0.0.1;
#}
# pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
#
#location ~ \.php$ {
# root html;
# fastcgi_pass 127.0.0.1:9000;
# fastcgi_index index.php;
# fastcgi_param SCRIPT_FILENAME /scripts$fastcgi_script_name;
# include fastcgi_params;
#}
# deny access to .htaccess files, if Apache's document root
# concurs with nginx's one
#
#location ~ /\.ht {
# deny all;
#}
}
# another virtual host using mix of IP-, name-, and port-based configuration
#
#server {
# listen 8000;
# listen somename:8080;
# server_name somename alias another.alias;
# location / {
# root html;
# index index.html index.htm;
# }
#}
# HTTPS server
#
#server {
# listen 443;
# server_name localhost;
# ssl on;
# ssl_certificate cert.pem;
# ssl_certificate_key cert.key;
# ssl_session_timeout 5m;
# ssl_protocols SSLv2 SSLv3 TLSv1;
# ssl_ciphers HIGH:!aNULL:!MD5;
# ssl_prefer_server_ciphers on;
# location / {
# root html;
# index index.html index.htm;
# }
#}
}修改配置:
nginx
#user nobody;
worker_processes auto;
#error_log logs/error.log;
#error_log logs/error.log notice;
error_log logs/error.log warn;
pid logs/nginx.pid; # 取消注释,用于 systemd 服务管理
events {
worker_connections 1024;
use epoll;
multi_accept on;
}
http {
include mime.types;
default_type application/octet-stream;
charset utf-8;
server_tokens off; # 隐藏 Nginx 的版本
# 日志格式
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 logs/access.log main;
# 性能优化
sendfile on;
tcp_nopush on;
tcp_nodelay on;
keepalive_timeout 65;
keepalive_requests 100;
# 客户端限制
client_max_body_size 10m;
client_body_timeout 12s;
client_header_timeout 12s;
# 文件缓存
open_file_cache max=1000 inactive=20s;
open_file_cache_valid 30s;
open_file_cache_min_uses 2;
open_file_cache_errors on;
# 包含站点配置
include /etc/nginx/conf.d/*.conf;
include /etc/nginx/sites-enabled/*;
#gzip on;
server {
listen 80;
server_name localhost;
#charset koi8-r;
#access_log logs/host.access.log main;
location / {
root html;
index index.html index.htm;
}
#error_page 404 /404.html;
# redirect server error pages to the static page /50x.html
#
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root html;
}
# proxy the PHP scripts to Apache listening on 127.0.0.1:80
#
#location ~ \.php$ {
# proxy_pass http://127.0.0.1;
#}
# pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
#
#location ~ \.php$ {
# root html;
# fastcgi_pass 127.0.0.1:9000;
# fastcgi_index index.php;
# fastcgi_param SCRIPT_FILENAME /scripts$fastcgi_script_name;
# include fastcgi_params;
#}
# deny access to .htaccess files, if Apache's document root
# concurs with nginx's one
#
#location ~ /\.ht {
# deny all;
#}
}
# another virtual host using mix of IP-, name-, and port-based configuration
#
#server {
# listen 8000;
# listen somename:8080;
# server_name somename alias another.alias;
# location / {
# root html;
# index index.html index.htm;
# }
#}
# HTTPS server
#
#server {
# listen 443;
# server_name localhost;
# ssl on;
# ssl_certificate cert.pem;
# ssl_certificate_key cert.key;
# ssl_session_timeout 5m;
# ssl_protocols SSLv2 SSLv3 TLSv1;
# ssl_ciphers HIGH:!aNULL:!MD5;
# ssl_prefer_server_ciphers on;
# location / {
# root html;
# index index.html index.htm;
# }
#}
}创建静态资源服务器配置
创建网站目录
bash
# 创建网站根目录
sudo mkdir -p /var/www/static.example.com/{html,logs,temp,cache}
sudo mkdir -p /var/www/static.example.com/html/{images,css,js,fonts,downloads}添加测试文件
bash
sudo tee /var/www/static.example.com/html/index.html << 'EOF'
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>静态资源服务器</title>
<link rel="stylesheet" href="/css/style.css">
</head>
<body>
<h1>🎉 欢迎来到静态资源服务器!</h1>
<p>这是一个由 Nginx 驱动的静态资源服务器。</p>
<p>功能特性:</p>
<ul>
<li>📁 文件浏览与下载</li>
<li>⚡ Gzip 压缩</li>
<li>🔐 HTTPS 支持</li>
<li>📱 响应式设计</li>
<li>🔍 搜索引擎优化</li>
</ul>
<h2>测试资源:</h2>
<div style="margin: 20px 0;">
<a href="/images/nginx.png" style="padding: 10px; background: #4CAF50; color: white; text-decoration: none; border-radius: 5px;">
下载 Nginx Logo
</a>
<a href="/downloads/" style="padding: 10px; background: #2196F3; color: white; text-decoration: none; border-radius: 5px; margin-left: 10px;">
浏览下载目录
</a>
</div>
<footer style="margin-top: 50px; color: #666;">
<p>服务器时间: <span id="datetime"></span></p>
<p>Nginx 静态服务器 v1.0</p>
</footer>
<script>
document.getElementById('datetime').textContent = new Date().toLocaleString('zh-CN');
</script>
</body>
</html>
EOF创建样式文件
bash
sudo tee /var/www/static.example.com/html/css/style.css << 'EOF'
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
line-height: 1.6;
color: #333;
max-width: 1200px;
margin: 0 auto;
padding: 20px;
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
min-height: 100vh;
}
.container {
background: white;
border-radius: 10px;
padding: 40px;
box-shadow: 0 20px 60px rgba(0,0,0,0.3);
margin: 20px 0;
}
h1 {
color: #2c3e50;
margin-bottom: 20px;
font-size: 2.5em;
background: linear-gradient(45deg, #667eea, #764ba2);
-webkit-background-clip: text;
-webkit-text-fill-color: transparent;
}
h2 {
color: #3498db;
margin: 30px 0 15px 0;
border-bottom: 2px solid #3498db;
padding-bottom: 5px;
}
p {
margin: 10px 0;
font-size: 1.1em;
color: #555;
}
ul {
margin: 20px 0;
padding-left: 20px;
}
li {
margin: 8px 0;
font-size: 1.05em;
color: #444;
}
footer {
margin-top: 40px;
padding-top: 20px;
border-top: 1px solid #eee;
text-align: center;
font-size: 0.9em;
color: #888;
}
@media (max-width: 768px) {
body {
padding: 10px;
}
.container {
padding: 20px;
}
h1 {
font-size: 2em;
}
}
EOF设置权限:
bash
# 设置权限
sudo chown -R nobody:nobody /var/www/static.example.com
sudo chmod -R 755 /var/www/static.example.com创建服务器配置文件
创建配置文件 /etc/nginx/sites-available/static.example.com.conf
nginx
# 静态资源服务器配置
server {
listen 80;
listen [::]:80;
server_name static.example.com www.static.example.com;
root /var/www/static.example.com/html;
# 访问日志
access_log /var/www/static.example.com/logs/access.log;
error_log /var/www/static.example.com/logs/error.log;
# 默认索引文件
index index.html index.htm;
# 主位置块
location / {
try_files $uri $uri/ =404;
# 安全头
add_header X-Frame-Options "SAMEORIGIN" always;
add_header X-Content-Type-Options "nosniff" always;
add_header X-XSS-Protection "1; mode=block" always;
add_header Referrer-Policy "strict-origin-when-cross-origin" always;
# 禁用隐藏文件的访问
location ~ /\. {
deny all;
access_log off;
log_not_found off;
}
}
# 静态资源缓存优化
location ~* \.(js|css|png|jpg|jpeg|gif|ico|svg|woff|woff2|ttf|eot)$ {
expires 1y;
add_header Cache-Control "public, immutable";
add_header Pragma "public";
add_header Vary "Accept-Encoding";
# 开启文件预读
open_file_cache max=1000 inactive=20s;
open_file_cache_valid 30s;
open_file_cache_min_uses 2;
# 尝试压缩版本
gzip_static on;
# 防盗链
valid_referers none blocked server_names *.example.com;
if ($invalid_referer) {
return 403;
}
}
# 视频和音频文件
location ~* \.(mp4|webm|ogg|mp3|wav|flac)$ {
expires 6M;
add_header Cache-Control "public";
# 启用伪流媒体
mp4;
mp4_buffer_size 4M;
mp4_max_buffer_size 10M;
}
# 下载目录 - 启用目录列表
location /downloads/ {
autoindex on;
autoindex_exact_size off; # 显示文件大小(K/M/G)
autoindex_localtime on; # 使用本地时间
# 目录列表样式
add_header Content-Type "text/html; charset=utf-8";
# 下载文件缓存
location ~* \.(zip|tar|gz|bz2|7z|rar)$ {
expires 7d;
add_header Cache-Control "public";
}
}
# 禁止访问某些敏感文件
location ~* \.(log|sql|bak|conf|cfg)$ {
deny all;
access_log off;
log_not_found off;
}
# 重写 favicon.ico
location = /favicon.ico {
log_not_found off;
access_log off;
expires max;
}
# 重写 robots.txt
location = /robots.txt {
allow all;
log_not_found off;
access_log off;
}
# 自定义错误页面
error_page 404 /404.html;
error_page 500 502 503 504 /50x.html;
location = /404.html {
root /var/www/static.example.com/html;
internal;
}
location = /50x.html {
root /var/www/static.example.com/html;
internal;
}
# 健康检查端点
location = /health {
access_log off;
return 200 "healthy\n";
add_header Content-Type text/plain;
}
# 文件上传限制
client_max_body_size 100M;
client_body_buffer_size 128k;
client_body_temp_path /var/www/static.example.com/temp;
# 设置连接超时
send_timeout 300s;
proxy_connect_timeout 300s;
proxy_send_timeout 300s;
proxy_read_timeout 300s;
}优化配置
创建通用优化配置文件 /etc/nginx/conf.d/optimization.conf:
nginx
# 压缩配置
gzip on;
gzip_vary on;
gzip_proxied any;
gzip_comp_level 6;
gzip_buffers 16 8k;
gzip_http_version 1.1;
gzip_min_length 1024;
gzip_types
application/atom+xml
application/javascript
application/json
application/ld+json
application/manifest+json
application/rss+xml
application/vnd.geo+json
application/vnd.ms-fontobject
application/x-font-ttf
application/x-web-app-manifest+json
application/xhtml+xml
application/xml
font/opentype
image/bmp
image/svg+xml
image/x-icon
text/cache-manifest
text/css
text/plain
text/vcard
text/vnd.rim.location.xloc
text/vtt
text/x-component
text/x-cross-domain-policy;
# Brotli 压缩(如果支持)
# brotli on;
# brotli_comp_level 6;
# brotli_types text/plain text/css text/xml text/javascript
# application/javascript application/xml+rss application/atom+xml
# image/svg+xml;
# 安全头
add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;
add_header Content-Security-Policy "default-src 'self'; script-src 'self' 'unsafe-inline'; style-src 'self' 'unsafe-inline'; img-src 'self' data: https:;" always;
add_header Permissions-Policy "camera=(), microphone=(), geolocation=(), payment=()" always;
add_header X-Permitted-Cross-Domain-Policies "none" always;
add_header X-Download-Options "noopen" always;
add_header Clear-Site-Data "\"cache\", \"cookies\", \"storage\"" always;
# 缓存控制
map $sent_http_content_type $expires {
default off;
text/html 1h;
text/css max;
application/javascript max;
application/json 1h;
~image/ max;
~font/ max;
~video/ 6M;
~audio/ 6M;
}
expires $expires;
# 限流配置
limit_req_zone $binary_remote_addr zone=api:10m rate=10r/s;
limit_req_zone $binary_remote_addr zone=static:10m rate=100r/s;
limit_conn_zone $binary_remote_addr zone=addr:10m;启用站点并测试
bash
# 创建符号链接启用站点
sudo ln -s /etc/nginx/sites-available/static.example.com.conf \
/etc/nginx/sites-enabled/
# 测试配置文件语法
sudo nginx -t
# 或使用 systemctl(如果已注册为服务)
sudo systemctl configtest nginx
# 重新加载配置(推荐使用 systemctl)
sudo systemctl reload nginx
# 或者使用 nginx 命令(如果未注册为服务)
# sudo nginx -s reload
# 检查 Nginx 状态
sudo systemctl status nginx
# 测试访问
curl -I http://localhost
# 或
curl http://localhost/health实际部署步骤
以下是在服务器 14.103.203.158 上实际执行的完整部署步骤:
1. 备份配置文件
bash
# 备份原始配置文件
cp /usr/local/nginx/conf/nginx.conf /usr/local/nginx/conf/nginx.conf.bak2. 更新主配置文件
bash
# 编辑 nginx.conf,应用优化配置
vi /usr/local/nginx/conf/nginx.conf
# 确保以下配置已更新:
# - worker_processes auto;
# - pid logs/nginx.pid; (取消注释)
# - 添加 include /etc/nginx/conf.d/*.conf;
# - 添加 include /etc/nginx/sites-enabled/*;3. 创建目录结构
bash
# 创建 Nginx 配置目录
mkdir -p /etc/nginx/{conf.d,sites-available,sites-enabled}
# 创建网站目录结构
mkdir -p /var/www/static.example.com/{html/{images,css,js,fonts,downloads},logs,temp,cache}4. 创建测试文件
bash
# 创建 index.html(参考文档中的内容)
cat > /var/www/static.example.com/html/index.html << 'EOF'
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>静态资源服务器</title>
<link rel="stylesheet" href="/css/style.css">
</head>
<body>
<h1>🎉 欢迎来到静态资源服务器!</h1>
<p>这是一个由 Nginx 驱动的静态资源服务器。</p>
<!-- 更多内容见文档 -->
</body>
</html>
EOF
# 创建 CSS 文件(参考文档中的内容)
cat > /var/www/static.example.com/html/css/style.css << 'EOF'
/* CSS 内容见文档 */
EOF
# 创建测试下载文件
echo "测试文件" > /var/www/static.example.com/html/downloads/test.txt5. 设置权限
bash
# 设置文件所有者和权限
chown -R nobody:nobody /var/www/static.example.com
chmod -R 755 /var/www/static.example.com6. 创建配置文件
bash
# 创建服务器配置文件
cat > /etc/nginx/sites-available/static.example.com.conf << 'EOF'
# 配置文件内容见文档
EOF
# 创建优化配置文件
cat > /etc/nginx/conf.d/optimization.conf << 'EOF'
# 优化配置内容见文档
EOF7. 启用站点
bash
# 创建符号链接启用站点
ln -sf /etc/nginx/sites-available/static.example.com.conf \
/etc/nginx/sites-enabled/static.example.com.conf8. 测试和重新加载
bash
# 测试配置文件语法
/usr/local/nginx/sbin/nginx -t
# 如果测试通过,重新加载配置
systemctl reload nginx
# 或
/usr/local/nginx/sbin/nginx -s reload9. 验证部署
bash
# 健康检查
curl http://localhost/health
# 测试主页(需要使用 Host 头)
curl -H "Host: static.example.com" http://localhost/
# 测试 CSS 文件
curl -H "Host: static.example.com" http://localhost/css/style.css
# 测试下载目录
curl -H "Host: static.example.com" http://localhost/downloads/
# 检查服务状态
systemctl status nginx部署注意事项
常见问题及解决方案
1. 模块未编译问题
如果遇到以下错误:
code
nginx: [emerg] unknown directive "gzip_static"
nginx: [emerg] unknown directive "mp4"解决方案:这些指令需要对应的模块支持。如果 Nginx 编译时未包含这些模块,需要:
bash
# 移除 gzip_static 指令
sed -i "/gzip_static on;/d" /etc/nginx/sites-available/static.example.com.conf
# 移除 mp4 相关指令
sed -i "/mp4;/d; /mp4_buffer_size/d; /mp4_max_buffer_size/d" \
/etc/nginx/sites-available/static.example.com.conf2. 访问域名问题
由于配置的 server_name 是 static.example.com,直接访问 IP 会匹配到默认的 localhost 服务器块。
解决方案:
方法 1:使用 Host 头访问
bash
curl -H "Host: static.example.com" http://14.103.203.158/方法 2:修改本地 hosts 文件(仅本地测试)
bash
# 在客户端机器上编辑 /etc/hosts (Linux/Mac) 或 C:\Windows\System32\drivers\etc\hosts (Windows)
14.103.203.158 static.example.com方法 3:修改 server_name 为实际域名或使用通配符
nginx
server_name _; # 匹配所有域名
# 或
server_name static.example.com 14.103.203.158; # 同时匹配域名和 IP3. 权限问题
如果遇到 403 Forbidden 错误,检查:
bash
# 检查目录权限
ls -la /var/www/static.example.com/html/
# 检查文件所有者
ls -la /var/www/static.example.com/html/index.html
# 确保 nginx 用户有读取权限
chown -R nobody:nobody /var/www/static.example.com
chmod -R 755 /var/www/static.example.com4. 配置文件包含路径问题
如果 Nginx 找不到包含的配置文件,检查:
bash
# 检查 nginx.conf 中的 include 路径是否正确
grep -E "include.*conf.d|include.*sites-enabled" /usr/local/nginx/conf/nginx.conf
# 确保目录存在
ls -la /etc/nginx/conf.d/
ls -la /etc/nginx/sites-enabled/部署后的验证命令
bash
# 1. 检查服务状态
systemctl status nginx
# 2. 检查进程
ps aux | grep nginx
# 3. 检查端口监听
netstat -tlnp | grep nginx
# 或
ss -tlnp | grep nginx
# 4. 测试健康检查
curl http://localhost/health
# 5. 测试主页(使用 Host 头)
curl -H "Host: static.example.com" http://localhost/
# 6. 检查日志
tail -f /var/www/static.example.com/logs/access.log
tail -f /var/www/static.example.com/logs/error.log
# 7. 检查配置文件
/usr/local/nginx/sbin/nginx -t监控和维护脚本
创建监控脚本 /usr/local/bin/check-static-server.sh:
bash
#!/bin/bash
# 监控静态服务器状态
LOG_FILE="/var/log/nginx/static-server-check.log"
DATE=$(date "+%Y-%m-%d %H:%M:%S")
echo "======= 静态服务器检查: $DATE =======" >> $LOG_FILE
# 检查 Nginx 服务状态(优先使用 systemctl)
if systemctl is-active --quiet nginx 2>/dev/null; then
echo "✅ Nginx 服务运行正常" >> $LOG_FILE
elif pgrep -x "nginx" > /dev/null; then
echo "⚠️ Nginx 进程运行但未注册为服务" >> $LOG_FILE
else
echo "❌ Nginx 未运行" >> $LOG_FILE
systemctl restart nginx 2>/dev/null || /usr/local/nginx/sbin/nginx
fi
# 检查端口监听
if netstat -tlnp | grep ":80 " | grep nginx > /dev/null; then
echo "✅ 80 端口监听正常" >> $LOG_FILE
else
echo "❌ 80 端口未监听" >> $LOG_FILE
fi
if netstat -tlnp | grep ":443 " | grep nginx > /dev/null; then
echo "✅ 443 端口监听正常" >> $LOG_FILE
fi
# 检查磁盘空间
DISK_USAGE=$(df -h /var/www | awk 'NR==2 {print $5}')
echo "📊 磁盘使用率: $DISK_USAGE" >> $LOG_FILE
# 检查日志大小
LOG_SIZE=$(du -sh /var/www/static.example.com/logs/ 2>/dev/null | cut -f1)
echo "📁 日志大小: ${LOG_SIZE:-0}" >> $LOG_FILE
# 健康检查
STATUS=$(curl -s -o /dev/null -w "%{http_code}" http://localhost/health 2>/dev/null || echo "FAIL")
if [ "$STATUS" = "200" ]; then
echo "💚 健康检查: 通过 ($STATUS)" >> $LOG_FILE
else
echo "💔 健康检查: 失败 ($STATUS)" >> $LOG_FILE
fi
echo "=====================================" >> $LOG_FILE性能测试
apache2-utils
在 CentOS 7.9 中,apache2-utils这个包被包含在 httpd-tools 包中
bash
# 更新系统包
sudo yum update -y
# 安装 httpd-tools(包含 ab 压力测试工具)
sudo yum install -y httpd-tools
# 检查 ab 工具是否安装成功
which ab
ab -V使用 ab 进行压力测试:
bash
# 基本用法
ab -n 1000 -c 10 http://localhost/
# 更详细的测试
ab -n 5000 -c 100 -k http://localhost/
# 测试并生成报告
ab -n 10000 -c 200 -g output.tsv http://localhost/常用参数说明:
bash
ab -n 1000 # 总请求数
-c 100 # 并发数
-k # 启用 HTTP Keep-Alive
-t 60 # 测试时间(秒)
-p post.txt # POST 数据文件
-T type # Content-Type
-H header # 自定义请求头
-C cookie # Cookie
-v 2 # 详细模式
-w # HTML 格式输出
-g file.tsv # 生成 gnuplot 数据文件压力测试示例:
bash
# 测试静态服务器
ab -n 10000 -c 200 -k -t 30 \
-H "Accept-Encoding: gzip" \
http://localhost/index.html
# 测试结果解读
# Requests per second: 326.60 [#/sec] (mean)
# Time per request: 3.062 [ms] (mean)
# Time per request: 0.015 [ms] (mean, across all concurrent requests)创建测试脚本
创建一个测试脚本 test_performance.sh:
bash
#!/bin/bash
echo "=== Nginx 静态服务器性能测试 ==="
echo "测试时间: $(date)"
echo
# 测试1:主页测试
echo "1. 主页压力测试:"
ab -n 10000 -c 200 -k http://localhost/ 2>/dev/null | grep -E "(Requests per second|Time per request|Failed requests)"
echo
echo "2. 静态文件测试:"
ab -n 5000 -c 100 -k http://localhost/css/style.css 2>/dev/null | grep -E "(Requests per second|Time per request)"
echo
echo "3. 图片文件测试:"
ab -n 3000 -c 50 -k http://localhost/images/nginx.png 2>/dev/null | grep -E "(Requests per second|Time per request)"运行测试:
bash
chmod +x test_performance.sh
./test_performance.sh日常维护命令
使用 systemctl 管理(推荐)
bash
# 启动服务
sudo systemctl start nginx
# 停止服务
sudo systemctl stop nginx
# 重启服务
sudo systemctl restart nginx
# 重新加载配置(不中断服务)
sudo systemctl reload nginx
# 查看服务状态
sudo systemctl status nginx
# 检查服务是否运行
sudo systemctl is-active nginx
# 检查服务是否已启用
sudo systemctl is-enabled nginx
# 启用开机自启
sudo systemctl enable nginx
# 禁用开机自启
sudo systemctl disable nginx
# 查看服务日志
sudo journalctl -u nginx
sudo journalctl -u nginx -f # 实时查看
sudo journalctl -u nginx --since "1 hour ago" # 查看最近1小时的日志使用 nginx 命令管理
bash
# 查看 Nginx 版本
nginx -v
# 查看编译参数
nginx -V
# 检查配置文件语法
nginx -t
sudo systemctl configtest nginx # 如果已注册为服务
# 重新加载配置(不中断服务)
nginx -s reload
# 重新打开日志文件
nginx -s reopen
# 优雅停止
nginx -s quit
# 快速停止
nginx -s stop查看进程和端口
bash
# 查看进程
ps aux | grep nginx
# 查看监听端口
netstat -tlnp | grep nginx
ss -tlnp | grep nginx
# 查看进程树
pstree -p | grep nginx查看日志
bash
# 查看错误日志(实时)
tail -f /usr/local/nginx/logs/error.log
# 或
tail -f /var/log/nginx/error.log
# 查看访问日志(实时)
tail -f /usr/local/nginx/logs/access.log
# 或
tail -f /var/log/nginx/access.log
# 查看最近的错误日志
tail -n 100 /usr/local/nginx/logs/error.log
# 搜索特定错误
grep -i error /usr/local/nginx/logs/error.log | tail -20快速部署脚本
以下是一个完整的部署脚本,可以直接在服务器上执行:
bash
#!/bin/bash
# 静态服务器快速部署脚本
# 适用于源码编译安装的 Nginx
set -e # 遇到错误立即退出
echo "🚀 开始部署静态服务器..."
# 1. 备份配置文件
echo "📋 备份配置文件..."
cp /usr/local/nginx/conf/nginx.conf /usr/local/nginx/conf/nginx.conf.bak
# 2. 创建目录结构
echo "📁 创建目录结构..."
mkdir -p /etc/nginx/{conf.d,sites-available,sites-enabled}
mkdir -p /var/www/static.example.com/{html/{images,css,js,fonts,downloads},logs,temp,cache}
# 3. 创建测试文件
echo "📄 创建测试文件..."
# index.html 和 style.css 需要手动创建或从文档复制
# 创建测试下载文件
echo "测试文件内容" > /var/www/static.example.com/html/downloads/test.txt
# 4. 设置权限
echo "🔐 设置权限..."
chown -R nobody:nobody /var/www/static.example.com
chmod -R 755 /var/www/static.example.com
# 5. 创建配置文件(需要手动创建或从文档复制)
echo "⚙️ 创建配置文件..."
# 注意:这里需要手动创建配置文件,或使用文档中的配置内容
# 6. 启用站点
echo "🔗 启用站点..."
ln -sf /etc/nginx/sites-available/static.example.com.conf \
/etc/nginx/sites-enabled/static.example.com.conf
# 7. 检查并移除不支持的指令
echo "🔍 检查配置文件..."
if /usr/local/nginx/sbin/nginx -t 2>&1 | grep -q "gzip_static"; then
echo "⚠️ 移除不支持的 gzip_static 指令..."
sed -i "/gzip_static on;/d" /etc/nginx/sites-available/static.example.com.conf
fi
if /usr/local/nginx/sbin/nginx -t 2>&1 | grep -q "mp4"; then
echo "⚠️ 移除不支持的 mp4 指令..."
sed -i "/mp4;/d; /mp4_buffer_size/d; /mp4_max_buffer_size/d" \
/etc/nginx/sites-available/static.example.com.conf
fi
# 8. 测试配置
echo "🧪 测试配置..."
/usr/local/nginx/sbin/nginx -t
# 9. 重新加载配置
echo "🔄 重新加载配置..."
systemctl reload nginx || /usr/local/nginx/sbin/nginx -s reload
# 10. 验证部署
echo "✅ 验证部署..."
echo "健康检查:"
curl -s http://localhost/health || echo "健康检查失败"
echo -e "\n服务状态:"
systemctl status nginx --no-pager | head -10
echo -e "\n✅ 部署完成!"
echo "📝 访问方式:"
echo " curl -H 'Host: static.example.com' http://localhost/"
echo " 或修改本地 hosts 文件: 14.103.203.158 static.example.com"