Nginx实用配置示例

Sakura 发布于 2024-04-01 470 次阅读


添加ssl证书

server {
    listen  443 ssl;
    server_name yourdomain.com;

    # 添加ssl证书
    ssl_certificate certs/yourdomain.com.pem;
    ssl_certificate_key certs/yourdomain.com.key;
    ssl_session_timeout 5m;
    ssl_protocols TLSv1.1 TLSv1.2 TLSv1.3;
    ssl_ciphers EECDH+CHACHA20:EECDH+AES128:RSA+AES128:EECDH+AES256:RSA+AES256:EECDH+3DES:RSA+3DES:!MD5;
    ssl_prefer_server_ciphers on;

    # 访问日志
    access_log /var/log/nginx/yourdomain.com.https.log;
}

http重定向https

server {
    listen 80;
    server_name yourdomain.com;
    rewrite ^(.*)$ https://$host$1 redirect;
}

后端服务接口

location /v1/ {
    proxy_pass http://127.0.0.1:8080/;
    proxy_read_timeout 30;
    proxy_redirect off;
    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 REMOTE-HOST $remote_addr;
}
# /结束,请求转发到后端服务器后,不会携带 /v1/。

访问日志

access_log /var/log/nginx/yourdomain.com.https.log;

请求体大小

client_max_body_size 100m;

H5自动适配

# 前端页面
set $html_root /var/html/yourdomain.com/;

# H5自动适配
if ($http_user_agent ~* (mobile|nokia|iphone|ipad|android|samsung|htc|blackberry)) {
    set $html_root /var/html/yourdomain.com/h5/;
}

location / {
    root $html_root/www/;
    index index.html;
    try_files $uri $uri/ /index.html;
}

location /admin/ {
    root $html_root;
    index index.html;
    try_files $uri $uri/ /admin/index.html;
}

#  目录结构
/var/html/yourdomain.com/
├── admin
│   └── index.html
├── www
│    └── index.html
└── h5
    ├── admin
    │   └── index.html
    └── www
        └── index.html

WebSocket

location /v1/ {
    proxy_pass http://127.0.0.1:8080/;
    proxy_http_version 1.1;
    proxy_set_header Upgrade $http_upgrade;
    proxy_set_header Connection "Upgrade";
}

开启gzip

gzip on;
gzip_min_length 10k;
gzip_buffers 4 16k;
gzip_comp_level 5;
gzip_types text/plain application/javascript application/x-javascript text/css application/xml text/javascript application/x-httpd-php image/jpeg image/gif image/png;
gzip_vary off;
gzip_disable "MSIE [1-8]\.";

静态资源缓存

location ~* \.(js|css|png|jpg|jpeg|gif|ico)$ {
    expires max;
    log_not_found off;
}