Nginx配置模板
nginx.conf
# For more information on configuration, see:
# * Official English Documentation: http://nginx.org/en/docs/
# * Official Russian Documentation: http://nginx.org/ru/docs/
user nginx;
worker_processes auto; #启动进程
error_log /var/log/nginx/error.log; #全局错误日志
pid /run/nginx.pid; #PID文件
# Load dynamic modules. See /usr/share/nginx/README.dynamic.
include /usr/share/nginx/modules/*.conf;
events {
worker_connections 1024; #单个后台worker process进程的最大并发链接数
}
http {
include mime.types;
default_type application/octet-stream;
# 启用gzip压缩来减轻服务器带宽
gzip on;
gzip_min_length 1k;
gzip_buffers 4 16k;
gzip_http_version 1.0;
gzip_comp_level 6; #设置数据的压缩等级,等级为1-9,压缩比从小到大
gzip_types text/plain text/css text/javascript application/json application/javascript application/x-javascript application/xml; #设置需要压缩的数据格式
gzip_vary on;
# 实现tomcat服务器的负载均衡
upstream tomcat_server {
server <IP>:8887;
server <IP>:8888;
server <IP>:8889;
}
server {
listen 80;
server_name localhost;
location / {
proxy_pass http://tomcat_server; #代理路径
proxy_redirect off;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header Host $http_host;
proxy_next_upstream http_502 http_504 error timeout invalid_header;
}
}
# 发布前端项目并反向代理后端api
server {
listen 8081;
server_name localhost;
location / {
root /usr/share/nginx/xxxx/xxxx; #定义前端项目根目录位置;
index index.html;
error_page 404 /index.html;
}
# 反向代理后端api,解决跨域问题
location /api {
rewrite ^/api/(.*)$ /$1 break; #重定向
proxy_pass http://localhost:80/; # 实际后端服务地址
}
}
# 发布静态资源
server {
listen 8082;
server_name localhost;
charset utf-8;
root /usr/share/nginx/xxxx/xxxx; #定义静态资源文件根目录位置;
location / {
add_header 'Access-Control-Allow-Origin' '*';
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS, PUT, DELETE';
add_header 'Access-Control-Allow-Headers' 'Content-Type';
autoindex on;# 显示目录
autoindex_exact_size on;# 显示文件大小
autoindex_localtime on;# 显示文件时间
# 注意:只做文件服务(只提供文件下载功能)时,下面两个指令最好加上;但如果需要在线预览mp4视频的话就需要注释掉
default_type 'application/octet-stream';
add_header Content-disposition "attachment";
}
}
}
小贴士:可以通过stub_status on
模块开启nginx工作状态(监控)
server {
listen xxxx;
server_name xxxx;
......
......
location /status {
stub_status on;
}
}