回到首页

nginx的用法

部署html文件

安装nginxsudo apt-get install nginx

启动nginx服务后查看nginx服务状态systemctl status nginx

nginx正常运行在80端口,访问http://localhost,能看到nginx配置的index.html网页内容。

部署html文件,配置好两点即可:http服务所在的端口,告诉请求方找nginx服务取;以及主机上html文件与服务器暴露出的文件路径的映射关系。

在/etc/nginx/nginx.conf中找到上述配置,如果没有找到,去nginx.conf中include的配置文件中找。我的nginx版本是1.18.0,最终在nginx.conf中include的/etc/nginx/sites-available/default文件中如下配置好端口和nginx网页根目录映射的目录:

listen 80 default_server;
root /usr/share/nginx/html;
这样本地访问的http://localhost对应的是/usr/share/nginx/html/index.html,自定义a.html文件放在/usr/share/nginx/html/a/b/c/d目录下,可通过http://localhost/a/b/c/d/a.html访问到。

设置txt文件自动下载

browser直接打开放在下载路径下的txt文件,无法下载到本地,有时甚至出现乱码。
打开/etc/nginx/sites-enabled/default编辑,增上红色所示代码

location / {
        # First attempt to serve request as file, then
        # as directory, then fall back to displaying a 404.
        try_files $uri $uri/ =404;
        if ($request_filename ~* ^.*?\.txt$){
                add_header Content-Disposition "attachment;";
        }        
}
参考自nginx强制下载txt等文件

本文创建于2021年 08月 08日 星期日 10:20:52 CST,修改于2021年10月31日15:15