三年经验的前端或多或少与 nginx 配置打过交道。
nginx 的重要性不言而喻。
本篇文章以前端的视角,介绍下 nginx 的常见配置,并通过 docker 的方式学习 nginx,这保证所有示例配置都能正常运行。
我将本文所有关于 docker/nginx 的配置放置在 simple-deploy,可克隆下来通过 docker compose 快速运行。
并将所有的接口示例维护在了 Learn Nginx By Docker 文档,并可通过 Apifox 打开并快速调试。
nginx 的配置文件
我们通过 nginx
镜像来了解 nginx 的配置文件都有哪些。
$ docker run -it --rm nginx:alpine sh
$ ls -lah /etc/nginx/
total 40K
drwxr-xr-x 3 root root 4.0K Nov 13 2021 .
drwxr-xr-x 1 root root 4.0K Jun 14 07:55 ..
drwxr-xr-x 2 root root 4.0K Nov 13 2021 conf.d
-rw-r--r-- 1 root root 1.1K Nov 2 2021 fastcgi.conf
-rw-r--r-- 1 root root 1007 Nov 2 2021 fastcgi_params
-rw-r--r-- 1 root root 5.2K Nov 2 2021 mime.types
lrwxrwxrwx 1 root root 22 Nov 13 2021 modules -> /usr/lib/nginx/modules
-rw-r--r-- 1 root root 648 Nov 2 2021 nginx.conf
-rw-r--r-- 1 root root 636 Nov 2 2021 scgi_params
-rw-r--r-- 1 root root 664 Nov 2 2021 uwsgi_params
在 nginx
中,其中比较重要的有以下几个文件,而它们都是有层层关联的:
/etc/nginx/nginx.conf
/etc/nginx/conf.d/default.conf
/etc/nginx/nginx.conf
nginx 主配置文件,引用了 /etc/nginx/conf.d/
目录下的所有配置文件。
user nginx;
worker_processes auto;
error_log /var/log/nginx/error.log notice;
pid /var/run/nginx.pid;
events {
worker_connections 1024;
}
http {
include /etc/nginx/mime.types;
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 65;
#gzip on;
include /etc/nginx/conf.d/*.conf;
}
/etc/nginx/conf.d/default.conf
server {
listen 80;
server_name localhost;
#access_log /var/log/nginx/host.access.log main;
location / {
root /usr/share/nginx/html;
index index.html index.htm;
}
#error_page 404 /404.html;
# redirect server error pages to the static page /50x.html
#