一、前言
Nginx是一款当前比较流行的web服务软件和反向代理软件,这里主要是总结一下平时部署配置nginx的时候总结一些知识点,比如web配置、反向代理配置、负载均衡配置等,笔记中的nginx均是部署在docker中,所以有时候的配置需要针对docker有所考量,特别是映射目录的时候一定要概念清晰,同时笔记中各种配置的记录不是按照文档中来的,是平时工作当中碰到了就记下来了,没有特定的顺序
二、nginx配置
下面是一个使用docker部署的nginx的最基本的web服务
nginx_linuxwt:
restart: always
image: nginx:1.15
container_name: nginx_linuxwt
volumes:
- ./html:/www/html
- ./nginx.conf:/etc/nginx/nginx.conf
- ./nginx_flask.conf:/etc/nginx/conf.d/default.conf
- /etc/localtime:/etc/localtime
- /etc/timezone:/etc/timezone
privileged: true
ports:
- "80:80"
上面最重要的两个配置文件是nginx_flask.conf和nginx.conf,其基础配置如下
cat nginx_flask.conf
server {
listen 80;
location / {
root /www/html;
index index.html;
}
}
cat nginx.conf
user root;
worker_processes 1;
# 错误日志
error_log /var/log/nginx/error.log warn;
pid /var/run/nginx.pid;
events {
worker_connections 1024;
}
http {
include /etc/nginx/mime.types;
server_tokens off;
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 /var/log/nginx/access.log main;
sendfile on;
#tcp_nopush on;
keepalive_timeout 3000;
autoindex off;
gzip on;
gzip_min_length 1k;
gzip_buffers 4 16k;
gzip_http_version 1.1;
gzip_comp_level 2;
# 下面是一整段
gzip_types text/plain image/png application/javascript application/x-javascript text/javascript text/css application/xml image/x-icon application/xml+rss
application/json;
gzip_vary on;
gzip_proxied expired no-cache no-store private auth;
gzip_disable "MSIE [1-6]\.";
include /etc/nginx/conf.d/*.conf;
}
2.1.autoindex配置
nginx默认是不允许列出整个目录的,如果需要列出整个目录,需要通过配置以下三个参数开启此功能
autoindex on;表示打开目录的流量功能,默认是off
autoindex_exact_size off;表示显示文件的大概大小,默认是on,表示显示文件的精确大小
autoindex_localtime on;表示显示文件时间为系统时间,默认为off,显示GMT时间
cat nginx_flask.conf
server {
listen 80;
location / {
root /www/html;
index index.html;
autoindex on;
autoindex_exact_size off;
autoindex_localtime on;
}
}
2.2.nginx的反向代理配置
cat nginx_flask.conf
server {
listen 80;
location / {
proxy_set_header Host $http_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;ed-Proto $scheme;
proxy_pass http://10.8.8.1:8080;
proxy_pass_header Server;
}
}
上面的这个配置时表示http请求从80端口进入,然后反向代理跳转至服务器10.8.8.1的8080端口
上面有几个参数需要注意:
proxy_set_header Host $http_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;
上面这几个参数可以使得后端服务器获取客户端的真实ip
2.2.nginx乱码
有时候nginx显示的页面会出现乱码,解决方式:
server {
listen 80;
default_type 'text/html';
charset utf-8;
location / {
root /www/html1;
index index.html;
}
}