做为一名前端开发者,使用nginx配置静态web服务器是咱们常常使用的功能之一。此外对于nginx的其余功能,好比说负载均衡,反向代理之类的咱们接触的比较少。可是我认为要想掌握nginx这一大利器,咱们就须要去多多了解他所具有的功能,以及nginx的设计架构和原理,而若是想要快速的掌握这块,我以为动手去使用nginx是最快的途径之一。本章记录下搭建nginx的过程。javascript
在开始搭建文件服务器以前咱们先要了解下实现这块的相关api,在nginx模块中有以下 ngx_http_autoindex_module,模块处理以斜杠('/')结尾的请求,并生成目录列表。css
apt install nginx
复制代码
http{
server{
location /test{
alias /var/www; //目录路径
autoindex on;
}
}
}
复制代码
nginx -t //返回ok则说名语法没问题
nginx -s start
复制代码
当咱们不知足于nginx自带的文件服务器样式时候,咱们可使用facyindex来从新格式化其目录样式,具体操做以下html
yum install https://extras.getpagespeed.com/redhat/7/x86_64/RPMS/nginx-module-fancyindex-1.12.0.0.4.1-1.el7.gps.x86_64.rpm
复制代码
yum install nginx-module-fancyindex
复制代码
load_module "modules/ngx_http_fancyindex_module.so";
复制代码
//若是系统是ubuntu那比较简单前端
sudo apt-get install nginx-extras
复制代码
location /teset {
alias /var/www; //目录路径
fancyindex on; # Enable fancy indexes.
fancyindex_exact_size off; # Output human-readable file sizes.
}
复制代码
//容许在生成的清单中插入指向CSS样式表的连接。该连接将插入到内置CSS规则以后,所以您能够覆盖默认样式。
fancyindex_css_href
//指定应该将哪一个文件插入到目录清单的底部。若是设置为空字符串,则发送模块提供的默认页脚。
fancyindex_footer
//指定应该将哪一个文件插入到目录清单头部。若是设置为空字符串,则发送模块提供的默认页眉。
fancyindex_header
//指定将不会在生成的清单中显示的文件名列表
fancyindex_ignore
//Enables showing file times as local time. Default is “off” (GMT time).
fancyindex_localtime
复制代码
nginx -t
nginx -s reload
复制代码
至此咱们能够实现一个比默认格式更美观的文件服务器,以下图: java
注:fancyindex-theme是基于fancyindex的插件,提供了更加优美的文件展现页面。以及一些检索操做。jquery
git clone https://github.com/Naereen/Nginx-Fancyindex-Theme
复制代码
cp Nginx-Fancyindex-Theme-light /var/www/Nginx-Fancyindex-Theme-light
复制代码
{
fancyindex_localtime on;
fancyindex_header "/Nginx-Fancyindex-Theme-light/header.html";
fancyindex_footer "/Nginx-Fancyindex-Theme-light/footer.html";
}
复制代码
注:若是咱们在nginx中的配置location 为/test,那咱们在引入fancyindex_header和fancyindex_footer是就要以下写linux
{
fancyindex_header "/test/Nginx-Fancyindex-Theme-light/header.html";
fancyindex_footer "/test/Nginx-Fancyindex-Theme-light/footer.html";
}
复制代码
另外在/Nginx-Fancyindex-Theme-light/footer.html和fancyindex_header "/Nginx-Fancyindex-Theme-light/header.html"文件中须要在引入外部文件的地方都加上前缀testnginx
<link rel="stylesheet" href="/test/Nginx-Fancyindex-Theme/styles.css">
<script type="text/javascript" src="/test/Nginx-Fancyindex-Theme/jquery.min.js"></script>
复制代码
这个是由于nginx路由匹配规则致使。git
本节主要是了解下nginx在搭建静态文件服务器中的使用,虽然默认的nginx文件模块已经能知足咱们功能需求,但做为一名前端工程是追求友好交互是必不可少的品质之一。另外,在这个大前端时代,对于前端开发来讲掌握nginx那咱们就至关于在前端领域多了另外一种可能。github