Nginx Config

Installation and Setup

Installation

Linux CentOS

sudo yum install nginx

Linux Ubuntu

sudo apt-get install nginx

MacOS

brew install nginx

enable service

# enable service on boot
sudo systemctl enable nginx
# start service
sudo systemctl start nginx

check the nginx version

nginx -v

update config

edit config file

sudo vim /etc/nginx/nginx.conf

test config

sudo nginx -t

reload service

sudo nginx -s reload

Common Issues

Fix Router History Mode refresh 404

location / {
root /home/www/dist/;
index index.html index.htm;
try_files $uri $uri/ @router;
# 对 HTML 文件禁用缓存
location ~* \.html$ {
add_header Cache-Control "no-cache, no-store, must-revalidate";
add_header Pragma "no-cache";
add_header Expires 0;
}
# 对 JS/CSS 等静态资源可以长期缓存(因为有 hash)
location ~* \.(js|css|png|jpg|jpeg|gif|ico|svg|woff|woff2)$ {
add_header Cache-Control "public, max-age=31536000, immutable";
}
}

Configure SSL

worker_processes 1;
events {
worker_connections 1024;
}
http {
include mime.types;
default_type application/octet-stream;
sendfile on;
keepalive_timeout 65;
gzip on;
server {
listen 443 ssl;
server_name xxx.com www.xxx.com;
ssl_certificate /home/ssl/xxx.com.pem;
ssl_certificate_key /home/ssl/xxx.com.key;
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root html;
}
}
server {
listen 80;
server_name xxx.com www.xxx.com;
return 301 https://xxx.com$request_uri;
}
}

Configure Websocket Proxy

location /ws/ {
proxy_pass http://127.0.0.1:8080;
proxy_http_version 1.1;
# WebSocket 升级
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
# 传递客户端信息
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;
# 超时设置(WebSocket 长连接需要较长超时)
proxy_connect_timeout 60s;
proxy_send_timeout 60s;
proxy_read_timeout 3600s; # 1小时,防止空闲连接被断开
}

Configure Gzip

# 动态压缩(实时压缩响应内容)
gzip on;
gzip_min_length 1k; # 小于 1k 的文件不压缩
gzip_comp_level 5; # 压缩级别 1-9,5 是性能与压缩率的平衡点
gzip_buffers 16 8k; # 压缩缓冲区
gzip_vary on; # 添加 Vary: Accept-Encoding 响应头
gzip_proxied any; # 对所有代理请求启用压缩
gzip_disable "MSIE [1-6]\."; # 禁用对旧版 IE 的压缩
# 压缩的 MIME 类型(注意:图片已是压缩格式,不需要 gzip)
gzip_types
text/plain
text/css
text/xml
text/javascript
application/json
application/javascript
application/x-javascript
application/xml
application/xml+rss
application/vnd.ms-fontobject
font/ttf
font/opentype
font/x-woff
image/svg+xml;

如果需要提供预压缩的静态文件(需要 ngx_http_gzip_static_module 模块):

# 静态压缩(直接发送预先压缩好的 .gz 文件)
# 需要模块:ngx_http_gzip_static_module
# 检查是否支持:nginx -V 2>&1 | grep gzip_static
gzip_static on; # 优先发送 .gz 文件,不存在则回退到动态压缩

Read Next

Gitea Drone Code Hosting and Pipeline Deployment

Read Previous

CSS Base