Nginx Config

nginx configuration for common use cases

installation and configuration

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 "E:\WorkSpaces\www"; # /home/www (linux)
index index.html index.htm;
try_files $uri $uri/ @router;
}
location @router {
rewrite ^(.*)$ /index.html last;
}

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;
location / {
root /home/web_server/static;
index index.html index.htm;
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root html;
}
}
server {
listen 80;
server_name xxx.com www.xxx.com;
rewrite ^(.*)$ https://$host$1 permanent;
}
}

Configure Websocket Proxy

location / {
proxy_pass http://127.0.0.1:8080;
proxy_http_version 1.1;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
proxy_set_header Host $host;
}

Configure Gzip

gzip on;
gzip_min_length 1k; # 响应数据大于1k时进行压缩
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 application/vnd.ms-fontobject font/ttf font/opentype font/x-woff image/svg+xml;
gzip_vary on;
gzip_buffers 32 4k; # 动态压缩缓冲区大小
gzip_static always; # 始终发送静态的gzip压缩数据
gunzip on; # 如果客户端不支持gzip,则解压后发送
gunzip_buffers 32 4k; # 解压缓冲区大小